Basic ideas
The basic idea of the binary insertion sort is the same as the direct insert sort, when inserting the i ( i Span style= "Font-family:mathjax_main; padding-left:0.278em; "id=" mathjax-span-44 "class=" Mo ">≥ 1 ) Element, the front i? 1 Elements have been sequenced. The difference is in finding the insertion position in different ways. The binary insertion sort is used to find the insertion position using the binary lookup method.
The basic idea of the binary lookup method is to compare the values of the elements to be interpolated with the values of the intermediate elements of the current lookup sequence, dividing the intermediate elements of the current lookup sequence to determine whether the interpolated element is on the left or right side of the current lookup sequence, assuming it is on its left. The left sequence is the current lookup sequence. The right side is similar. In accordance with the above method, the new sequence is processed recursively. Until the length of the current lookup sequence is less than 1 o'clock the discovery process ends.
Code
//The pending data is stored in array a. And the left and right borders of the pending sequence. Public void Binaryinsertsort(int[] A,intLeftintright) {intLow, middle, high;intTemp for(inti = left +1; I <= right; i++) {temp = A[i]; Low = left; High = i-1; while(Low <= High) {middle = (low + high)/2;if(A[i] < A[middle]) high = middle-1;ElseLow = middle +1; } for(intj = i-1; J >= Low; j--) A[j +1] = A[j]; A[low] = temp; }}
Performance analysis
- Complexity of Time
Binary insert sort is suitable for scenes with a large number of records, compared to the direct insertion sort. Binary the insertion sort takes much less time to find the insertion position, but the binary insert sort is the same as the direct insertion sort in the record move, so its time complexity is o ( n 2 ) 。
Second, the number of records for the binary insert sort is unrelated to the initial sequence. The number of binary times is certain because each sort of binary looks for the insertion position. Binary once more, so the number of times is also certain.
- Complexity of space
As with the direct insert sort, the O (1) 。
- Stability
Binary insertion sorting is a stable sorting algorithm.
Binary method (binary) insertion sorting algorithm of sorting algorithm