Followings are written in a ppt about Insertion Sort in my class:
void insertionSort(DataType theArray[], int n) {
for (int unsorted = 1; unsorted < n; ++unsorted) {
DataType nextItem = theArray[unsorted];
int loc = unsorted;
for (;(loc > 0) && (theArray[loc-1] > nextItem); --loc)
theArray[loc] = theArray[loc-1];
theArray[loc] = nextItem;
}
}
–
Running time depends on not only the size of the array but also the contents of the array.
Best-case: O(n)
Array is already sorted in ascending order.
Inner loop will not be executed.
>>>> The number of moves: 2*(n-1) O(n)
>>>> The number of key comparisons: (n-1) O(n)
Worst-case: O(n2)
Array is in reverse order:
Inner loop is executed p-1 times, for p = 2,3, …, n
The number of moves: 2*(n-1)+(1+2+...+n-1)= 2*(n-1)+ n*(n-1)/2 O(n2)
The number of key comparisons: (1+2+...+n-1)= n*(n-1)/2 O(n2)
Average-case: O(n2)
We have to look at all possible initial data organizations.
So, Insertion Sort is O(n2)
What exacly are move and key comparison?? I couldn’t find an explanaiton on Google.
Let me word the algorithm first.
0to indexloc - 1is sorted in ascending order and indexlocton - 1is unsorted.loc, find its correct place in sorted part of the array and insert it there.So now there are two loops:
loc = 1toloc = n, basically partitions the array in sorted and unsorted part.locin the sorted part of array (0toloc - 1).For the inner loop, to find correct location, you have to compare element at
locwith, in worst case, all the elements in sorted part of array. This is key comparison.To insert, you have to create a void in sorted part of the array for element at
loc. This is done by swapping each element in sorted part to the next element. This is move.