Insertion sort should be fine, if you choose to code it yourself rather than using the language provided sort functions.
- It performs really well when the list is almost sorted (Though it is of Order O(N^2), if the list is almost sorted, the inner loop will not be executed often)
- It is pretty easy to implement.
Presenting the Python implementation of Insertion Sort.
Program
def InsertionSort(Array):
Total = 0
for i in xrange(1, len(Array)):
j, I, = i - 1, i
while j >= 0 and Array[I] > Array[j]:
Array[I], Array[j] = Array[j], Array[I]
j, I, Total = j - 1, I - 1, Total + 1
print "Insertion Sort Total Operations :", Total
Output
Worstcase
TestArray = range(1, 11)
InsertionSort(TestArray)
Insertion Sort Total Operations : 45
Bestcase
TestArray = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
InsertionSort(TestArray)
Insertion Sort Total Operations : 0
90% Sorted Array
TestArray = [1, 9, 8, 7, 6, 5, 4, 3, 2, 10]
InsertionSort(TestArray)
Insertion Sort Total Operations : 17
Half Sorted Array
TestArray = [10, 9, 8, 7, 6, 1, 2, 3, 4, 5]
InsertionSort(TestArray)
Insertion Sort Total Operations : 10