Insertsort: (in ascending order, for example)The basic idea of inserting a sort is:each time a pending record is placed, the size of its keyword is inserted into the appropriate position in the ordered area that was previously ordered until all records have been inserted. Suppose that the records to be sorted are stored in the array R[0..N], the initial r[0] is an ordered area, R[1..N] is an unordered area, starting with I=1, and then inserting r[i] into the ordered area R[0..i-1], a sequential area containing n records is generated.
based on the idea of insertion sequencing, we can write the following code:
void Insertsort (int *arr, int len) {int i = 0;int j = 0;int tmp = 0;for (i = 1; i < Len; i++) {tmp = Arr[i];for (j = i; j>0&&arr[j-1]>tmp; j--) //Find a correct position in the ordered area {arr[j] = arr[j-1]; Move the current record back}arr[j] = tmp; Insert TMP into the found location}}
optimization: Binary Insertnow that the ordered area is orderly, we can use the idea of binary to find this position in an orderly area when we are looking for a suitable location.
The code is as follows:
void Insertsort (int *arr, int len) {int i = 0;int j = 0;int tmp = 0;int mid = 0;int k = 0; for (i = 1; l < Len; i++) {tmp = Arr[i];int left = 0;int right = I-1;mid = (left&right) + ((left^right) >> 1 ); Averaging can be prevented from spilling while (left<=right) //using BinarySearch to find an appropriate position in the ordered area {if (arr[mid]>tmp) ///In this case, The location of TMP to be inserted must be less than or equal to Mid{right = Mid-1;k = mid;} else if (Arr[mid] <=tmp) //In this case, the location of TMP to be inserted must be greater than Mid{left = Mid+1;k = mid+1; } Mid = (left&right) + ((left^right) >> 1);} for (j = i; j>k; j--) //move backward all elements of this position {arr[j] = arr[j-1];} ARR[K] = tmp; Place tmp in this position}}
Note: This optimization reduces the number of times an ordered area is compared, but does not reduce the number of times the element is moved.
Sort--insertsort Optimization