以下是我班上关于插入排序的ppt写的:
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)
什么是移动和关键比较?我在谷歌上找不到解释。