Binary insertion sort) is an improvement for direct insertion of sorting algorithms, that is, the elements are constantly inserted into the sequence blocks in the sorted order. Because the first half is divided into the sorted sequence, we do not need to look for the insertion point in sequence from the back to the back). We can use the half-lookup method to speed up the search for the insertion point.
Specific operations:
When a new element is inserted into an array in the sorted order, when looking for the insertion point, set the receiving element of the inserted area to a [low]. set the last element to a [high], and set m = (low + high)/2 to compare a [m] With the element to be interpolated. If the element to be interpolated is large, then a [m + 1] to a [high] is the new insert area. Otherwise, a [low] to a [s-1] is the new insert area. This is not true until low <= high. Then, the element after this position is moved one by one, and the element to be inserted is inserted into a [high + 1];
# Include <stdio. h> # include <stdlib. h> void swap (int arr [], int I, int j) {int temp; temp = arr [I]; arr [I] = arr [j]; arr [j] = temp;} void InsertSort (int arr [], int n) {int I; for (I = 1; I <n; I ++) // The cycle starts from the first 2nd array elements and shifts arr [0] As the originally sorted part {int j; int low = 0; // The maximum int high = I-1; // The maximum int temp = arr [I]; while (low <= high) {int m = (low + high)/2; if (temp <arr [m]) high = m-1; elselow = m + 1;} for (j = I-1; j> high; j --) arr [j + 1] = arr [j]; arr [high + 1] = temp ;}} void print (int arr [], int n) {int I; for (I = 0; I <n; I ++) {printf ("% d", arr [I]);} printf ("\ n");} int main () {int arr [] = {9, 1, 5, 8, 3, 7, 4, 6, 2 }; int n = sizeof (arr)/sizeof (arr [0]); printf ("Before sorting: \ n"); print (arr, n); InsertSort (arr, n); printf ("sorted: \ n"); print (arr, n); system ("pause"); return 0 ;}
This article is from "Li Haichuan" blog, please be sure to keep this source http://lihaichuan.blog.51cto.com/498079/1282132