Insertion sort principle: It works by constructing an ordered sequence, for unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert.
Insertion sorting core: Assuming that the first element is arranged, the elements after the arrangement are compared from the back to the front and moved one by one.
Insertion sort implementation:
- void insertion_sort(int a[], int n)
- {
- int i,j,tmp;
- for (i = 1; i < n; i++) {
- tmp = a[i];
- for (j = i - 1; j >= 0 && a[j] > tmp; j--) {
- a[j+1] = a[j];
- }
- a[j+1] = tmp;
- }
- }
void insertion_sort(int a[], int n) { int i,j,tmp; for (i = 1; i < n; i++) { tmp = a[i]; for (j = i - 1; j >= 0 && a[j] > tmp; j--) { a[j+1] = a[j]; } a[j+1] = tmp; } }
Insertion sort process animation:
Selection sort:
Similar to selection sort and insertion sort, both are in-place comparison sorts.
The core idea of selection sorting: the first part of the unsorted part is taken as the smallest (largest), and then compared with the rest in turn, if there is a smaller (larger), write down the subscript and use this as the new smallest (maximum) value, continue to compare, after one pass, then swap with the first one.
Selection sort implementation:
- void selection_sort(int a[], int n)
- {
- int i, j, k;
- for (i = 0; i< n-1; i++) {
- k = i;
- for (j = i+1; j < n; j++) {
- if (a[k] > a[j])
- k = j;
- }
- if (k != i) {
- int tmp = a[i];
- a[i] = a[k];
- a[k] = tmp;
- }
- }
- }
void selection_sort(int a[], int n) { int i, j, k; for (i = 0; i< n-1; i++) { k = i; for (j = i+1; j < n; j++) { if (a[k] > a[j]) k = j; } if (k != i) { int tmp = a[i]; a[i] = a[k]; a[k] = tmp; } } }
Selection sort process animation: