I've attempted coding the insertion sort algorithm in python -
def insertion(list):
checked = 2
while (checked <= len(list)):
for i in range(checked-1):
if list[checked-1] < list[i]:
list.insert(i, list[checked-1])
del list[checked]
checked+=1
return list
I measured the time it took to perform a 1000 item sort - 106.08099999999997 thousandths of a second
I found this to be rather slow since -
def bubbleSort(alist,n):
for j in range(1,n):
nextnum = alist[j]
i = j - 1
while i>=0 and alist[i]>nextnum:
alist[i + 1] = alist[i]
i = i - 1
alist[i + 1] = nextnum
Only took - 83.71800000000007 thousandths of a second
Is there any way I could make my code more efficient / would I have to use a different code? If so, which insertion sort implementation is the quickest in python? I'm aware that insertion sort isn't usually the best algorithm to use. This is just for my school work, so that I can understand the algorithms we learn better.
timeit? 2. if you want an efficient sorting algorithm don't use O(n^2) algorithms: use merge or quicksort. And if you know the range of the numbers you might be able to achieve linear time with radix or bucket sort