Home  >  Article  >  Java  >  How to insert elements into java array and quickly sort them

How to insert elements into java array and quickly sort them

PHPz
PHPzforward
2023-04-20 09:43:061314browse

1. Operate from the second element of the array. If it is found that the previous element is larger than it, move the previous element back until the element pointed by cur is greater than or equal to its previous element. At this time The position pointed by cur is the position where the element to be inserted should be inserted.

static int[] insertSort2(int[] array){
 
    int len = array.length;
 
    for (int begin = 1; begin < len; begin++){
 
        int cur = begin;
 
        int tmp = array[cur];
 
        while (cur > 0 && array[cur] < array[cur-1]){
 
            array[cur] = array[cur-1];
 
            cur--;
 
        }
 
        array[cur] = tmp;
 
    }
 
    return array;
 
}

2. Binary search reduces the number of comparisons, that is, cmp function calls, and also reduces the swap function calls. It is faster to find the position where the current element should be inserted, and then move it, which improves efficiency.

static int[] insertSort3(int[] array){
 
        int len = array.length;
 
 
 
        for (int begin = 1; begin < len; begin++){
 
            int v = array[begin];
 
            int insertIndex = search(array,begin);
 
            // 将 [insertIndex, begin) 范围内的元素往右边挪动一个单位
 
            for (int i = begin; i > insertIndex; i--){
 
                array[i] = array[i-1];
 
            }
 
            array[insertIndex] = v;
 
        }
 
        return array;
 
    }
 
    static int search(int[] array, int index){
 
        int begin = 0;
 
        int end = index;
 
        while(begin < end){
 
            int mid = (begin+end) >> 1;
 
            if (array[index] < array[mid]){
 
                end = mid;
 
            }else{
 
                begin = mid+1;
 
            }
 
        }
 
        return begin;
 
}

The above is the detailed content of How to insert elements into java array and quickly sort them. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete