import random import time myList = random.sample(range(1,100) ,10) print(myList) print( 'now sorting in ascending order') #range generate a sequence of int, #the number of int depends on its arg, listLen = len( myList ) #start timer startTime = time.time( ) for first in range(0, listLen -1): for e in range( first , listLen): if myList[ e ] < myList[ first ]: myList[ e ] , myList[ first ] = myList[ first ] , myList[ e ] #stop timer endTime = time.time( ) print( myList ) print( 'time taken : ' , endTime - startTime)
The above Python code is the steps for Selection Sort algorithm. It basically compares the 1st element with the rest of the elements in the list(array). If the 1st element is larger than any of the rest of the elements, then they will swap places.
After which the second element becomes the 1st element and the comparision starts again. The execution time is approximately 0.00003 seconds. Time complexity is O(n2).
It can also be use for descending order, just by comparing which number is smaller instead of which number is bigger.