1, when a new element is inserted into a sorted array, the first element of the area to be inserted (the sorted range) is set to A[low] and the end element is set to A[high when the insertion point is searched, and the element and a[m are inserted when the comparison is made.
2, where m= (Low+high)/2 compared, if smaller than the reference element, then select A[low] to a[m-1] for the new insertion area (that is, high=m-1),
3, otherwise select a[m+1] to A[high] for the new insertion area (that is, low=m+1),
4, so until Low<=high is not established, after this position, all elements are moved back one bit, and the new element is inserted into a[high+1].
Binary insert sorting algorithm is a stable sorting algorithm, which significantly reduces the number of keywords compared to the direct insertion algorithm, so the speed is faster than the direct insertion algorithm, but the number of records moved does not change, so the time complexity of binary insertion sort algorithm is still O (n^2), Same as the direct insert sort algorithm. additional space O (1).
Binary lookup only reduces the number of comparisons, but the element moves the same number of times, so the time complexity of O (n^2) is correct.
#include <iostream> using namespace std; Binary insert sort on the record array r, length of the array is void binsort (int *r,int length) {for (int i = 2;i <= length;i++) {int x
= R[i];
int low = 1;
int high = i-1;
Determine the insertion position while (low <= high) {int mid = (low + high)/2;
if (x < R[mid]) high = mid-1;
else Low = mid + 1;
The//record is moved backward for (int j = i-1;j >= low;j--) {r[j + 1] = R[j];
}//Insert record R[low] = x;
int main () {int a[] = {0,48,62,35,77,55,14,18};
Binsort (a,7);
for (int i = 1;i <= 7;i++) cout << a[i] << ""; }