I was playing around with simple sorting algorithms to become more familiar with them, and tried to create insertion sort from the description of the algorithm rather than the pseudocode. I made an algorithm that worked and that I thought fitted the description:
import random
nums = []
for i in range(10000):
nums.append(random.randrange(0, 1000))
def getSortedIndexForEle(ele, sorted):
for i in range(0, len(sorted)):
if ele < sorted[i]:
return i
return len(sorted)
def sort(lst):
sorted = []
for ele in lst:
sorted.insert(getSortedIndexForEle(ele, sorted), ele)
return sorted
print(sort(nums))
However the code did not match the algorithm compisition wise (but still produced the correct result) so I had another attempt:
import random
nums = []
for i in range(10000):
nums.append(random.randrange(0, 1000))
def sort(lst):
for i in range(1, len(lst)):
ele = lst[i]
j = i - 1
for k in range(j, -2, -1):
if ele >= lst[k]:
break
lst[k + 1] = lst[k]
lst[k + 1] = ele
sort(nums)
print(nums)
I believe this one is correct, and I compared it to the pseudocode and it does effectively the same thing.
My question is the first algorithm that I made, which did not fit the algorithm, executes in around half the time of the actual thing on my machine (using a list of length 10000, every element a random number). How can this be possible? Is my second algorithm not correct? I even tried a python example of the algorithm and that also took longer than my first one...
#define rand(x) 42.range(j, -2, -1)? Not familiar with python.