Insert sort directly above
Direct insert sort each round of comparisons requires that the elements to be processed be compared to each of the preceding elements. So is there a way to optimize and reduce the number of comparisons? The answer, of course, is that the binary insertion described below is one of the optimization algorithms for direct insertion sequencing.
Principle
The direct insertion sort is a one-to-two comparison, while the binary-insertion sort is the use of the binary search principle to compare the elements to be sorted with the intermediate elements (N/2) of the queue that are already queued on the left. Smaller then continues to compare with the middle element on the left side of the intermediate element, the larger is compared to the middle element on the right side of the middle element, until a suitable position is found, and then the subsequent elements of this position are moved backward, with the inserted elements placed in the appropriate position, so as to complete a round of sorting.
Complexity of
The average time complexity is O (n^2), and the spatial complexity is always 1. Best case, only a n-1 comparison is required and no swap is needed.
It is also a stable sort because it does not have the same sequence of numeric elements.
Code implementation
Package Mainimport ("FMT" "Math/rand" "Time") Func main () {var length = ten var list []int//with timestamp for seed generation with Number of machines to ensure that each run of the data does not repeat r: = Rand. New (Rand. Newsource (time. Now (). Unixnano ()))) for I: = 0; i < length; i++ {list = append (list, int (R.INTN))} FMT. PRINTLN (list) for i: = 1; i < length; i++ {//Use binary search to find the appropriate insertion position on the left side of the element to be queued P: = suitableindex (list, 0, i-1, i)//if the most suitable position is not the current position of the element to be placed, then once the appropriate position The elements are moved backwards one if p! = I {temp: = List[i] for j: = i; j > P; j--{list[j], Li ST[J-1] = list[j-1], List[j]} list[p] = temp} fmt. PRINTLN (list)}}func suitableindex (list []int, start int, end int, current int) int {//compared to the last beauty, compare the size of the position and the element to be ranked and returns the position of the larger value if start >= end {if List[start] < List[current] {return current} else { Return start}} Center: = (End-start)/2 + start//If the middle element is larger, continue to the leftSide looking. Conversely, right if list[center] > list[current] {return Suitableindex (list, start, center, current)} else { return Suitableindex (list, center+1, end, Current)}}
Run result