Several ways of direct insertion sort

Direct insertion sort time complexity

The average time complexity of insertion sort is also O(n^2), and the space complexity is a constant order of O(1). The specific time complexity is also related to the ordering of the array.

In insertion sorting, when the array to be sorted is in order, it is the optimal situation. You only need to compare the current number with the previous number. At this time, you need to compare N-1 times in total, and the time complexity is O(N) . The worst case is that the array to be sorted is in reverse order, and the number of comparisons is the most. The worst case is O(n^2).

Direct insertion sort stability
Direct insertion sort is a stable algorithm, which satisfies the definition of a stable algorithm.
Algorithm stability - Suppose there is a[i]=a[j] in the sequence, if before sorting, a[i] is in front of a[j]; and after sorting, a[i] is still in a[j] front. Then this sorting algorithm is stable!

The first

 public static void sort(Comparable[] arr){

        int n = arr.length;
        for (int i = 0; i < n; i++) {
            // 寻找元素 arr[i] 合适的插入位置
           for( int j = i ; j > 0 ; j -- )
                if( arr[j].compareTo( arr[j-1] ) < 0 )
                    swap( arr, j , j-1 );
                else
                    break;
        }
    }
    //核心代码---结束
    private static void swap(Object[] arr, int i, int j) {
        Object t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

The second

public static void sort(int[] a) {
        for (int i = 0, j = i; i < a.length - 1; j = ++i) {
            int ai = a[i + 1];
            while (ai < a[j]) {
                a[j + 1] = a[j];
                if (j-- == 0) {
                    break;
                }
            }
            a[j + 1] = ai;
        }
    }

The third

public static void selfSort2(int[] a){
        for (int i,j=0;++j<a.length;){
            int ai=a[i=j];
            if(a[i]<a[i-1]){
                while (--i>=0 && ai<a[i]){
                    a[i+1]=a[i];
                }
                a[i+1]=ai;
            }
        }
    }

The fourth

public static void StraightSort(int[] arr) {
        int tmp;
        int i;
        int j;
        for (i = 1; i < arr.length; i++) {
            tmp = arr[i];
            for (j = i - 1; j >= 0 && arr[j] > tmp; j--) {
                arr[j + 1] = arr[j];
            }
            arr[j + 1] = tmp;
        }
    }

 

Guess you like

Origin blog.csdn.net/GoSaint/article/details/113871181