Basic ideas
Binary the basic idea of the insertion sort is the same as the direct insertion sort, when inserting the element I (i≥1), the front I-1 elements are already sorted. The difference is that the method of finding the insertion position is different, and the binary insertion sort uses the binary lookup method to find the insertion position.
The basic idea of the binary lookup method is to compare the value of the element to be inserted with the value of the intermediate element of the current lookup sequence, dividing the middle element of the current lookup sequence to determine whether the element to be inserted is to the left or right of the current lookup sequence, or to the left of the current lookup sequence, and to the right. According to the above method, the new sequence is processed recursively until the length of the current lookup sequence is less than 1 o'clock the end of the discovery process.
Code
//data to be stored in array a, and left and right boundaries of the sequence to be queued 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 sorting is suitable for scenes with a large number of records, compared to the direct insert sort, the time taken by the binary insertion sort to find the insertion position is greatly reduced, but the binary insertion sort is the same as the direct insertion sort, so its time complexity is O (N2).
Second, the number of records compared to the binary insert sort is independent of the initial sequence. Because every trip sort binary to find the insertion position, the number of binary is certain, binary once to compare, so the number of comparisons is also certain.
- Complexity of space
As with the direct insert Sort, O (1).
- Stability
Binary insertion sorting is a stable sorting algorithm.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Binary method (binary) insertion sorting algorithm of sorting algorithm