Sort Algorithm


In [1]:
def sort_list(listed):
    
    # for each index number in the list starting at 1: 
    for i in range(1,len(listed)):
        
        # set the current value equal to the value at index, i: 
        currentvalue = listed[i]
#         print('current value:', currentvalue)
        
        # set position to index of the current value
        position = i
#         print('position:', position)
    
        # while the index number is greater than zero and the value before the current value 
        # is greater than the current value:
        while position>0 and listed[position-1]>currentvalue:
#                 print('Index position', position, 'is greater than 0')
#                 print('The value at index position', position, 'is', listed[position])
#                 print ('And the value at index position', position-1, 'is', listed[position-1], 'which is greater than', currentvalue)
#                 print('We change the value of', listed[position], 'to', listed[position-1])
                listed[position]=listed[position-1]
#                 print('We change the value of the variable storing index position from', position, 'to', position-1)
                position = position-1

    
        listed[position]=currentvalue
#         print('Index position equals 0, so we exit the loop')
#         print('And we set the value at index position', position, "to", currentvalue)

alist = [1, 5, 6, 8, 9, 0, 1, 4, 3, 5, 21, 67, 44]
sort_list(alist)
print(alist)


[0, 1, 1, 3, 4, 5, 5, 6, 8, 9, 21, 44, 67]

In [8]:
import random

lengths=[10,100,1000]
for x in lengths:  
    alist = random.sample(range(x), x)
    %time sort_list(alist)
    
# for a list length 10 
# CPU times: user 13 µs, sys: 1 µs, total: 14 µs
# Wall time: 16 µs

# for a list length 100
# CPU times: user 579 µs, sys: 1 µs, total: 580 µs
# Wall time: 583 µs

# for a list length 1000
# CPU times: user 82.3 ms, sys: 2.6 ms, total: 84.9 ms
# Wall time: 84.6 ms


CPU times: user 13 µs, sys: 1 µs, total: 14 µs
Wall time: 16 µs
CPU times: user 579 µs, sys: 1 µs, total: 580 µs
Wall time: 583 µs
CPU times: user 82.3 ms, sys: 2.6 ms, total: 84.9 ms
Wall time: 84.6 ms

In [ ]: