Insert in half

basic idea

The basic idea of ​​folded insertion sort is the same as that of direct insertion sort. When inserting the i(i≥1)i(i≥1) element, the first i−1i−1 elements are already sorted. The difference is that the method of finding the insertion position is different. The halved insertion sort uses the halved search method to find the insertion position.
The basic idea of ​​the split-half search method is to compare the value of the element to be inserted with the value of the middle element of the current search sequence, and use the middle element of the current search sequence as the boundary to determine whether the element to be inserted is on the left or right of the current search sequence, If it is on its left, the left sequence is used as the current search sequence, and the same is true for the right. According to the above method, the new sequence is recursively processed until the search process ends when the length of the current search sequence is less than 1.

Code

public class BinaryInsert {
    public static void binaryInsert(int[] arr) {
        int i =0;
        for(;i<arr.length;i++) {
            if(arr[i]>arr[i+1])
                break;
        }
        
        
        int left;
        int right;
        int mid;
        int tmp;
        for(; i<arr.length-1;i++) {   
            left = 0;
            right = i;
            tmp= arr[i+1];
            
            while(left<=right) {
                mid = (left+right)/2;
                if(arr[mid]>tmp)
                    right = mid - 1;
                else
                    left = mid + 1;
            }
              
            for(int j=i;j>=left;j--) {
                arr[j+1] = arr[j];
            }
            
            arr[left] = tmp;
        }
    }
    public static void main(String[] args) {
        int[] arr = {4, 6, 88, 1, 23, 12, 5};
        binaryInsert(arr);
        
        for(int i = 0; i<arr.length;i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output: 1 4 5 6 12 23 88

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325064419&siteId=291194637