Input: A sequence of n numbers {a3 , a1, a2,...,an } Output: A reordered sequence of the input {a1 , a2, a3,...,an } such that a1a2 a3 an
Insertion Sort
Sorted array/list is by inserting one item at a time Simple to implement Efficient on small data sets Efficient on already almost ordered data sets
Insertion Sort
Start with a sequence of size 1 Repeatedly insert remaining elements
This algorithm takes as parameter an array of the sequence numbers to be sorted A[1 n], the number of elements in the array is denoted by length[ A]. When this algorithm finish, the input array will contains the sorted sequence numbers (sort in place: the sorted items (output) occupy the same storage as the original ones (input) ).
Insertion Sort
void InsertionSort(double a[],int n){ for (int j = 2; j <= n; j++){ double key = a[j]; int i; for (i = j - 1; i > 0 && a[j] >key ; i--){ a[ i + 1] = a[ i]; } a[ i + 1] = key; } }