排序算法之直接插入排序

直接插入排序是将数组分成有序和无序两部分,每次将当前未排序的数和有序部分比较,移动有序部分,找到未排序数的插入点。

    private static void insertionSort(int[] a, int first, int end) {
        for (int i = first + 1; i <= end; i++) {
            int firstUnsorted = a[i];
            insertInorder(firstUnsorted,a,first,i-1);
        }
    }

    private static void insertInorder(int unsort, int[] a, int first, int end) {
        int index = end;
        while(index >= first && unsort < a[index] ){
            a[index + 1] = a[index];
            index --;
        }
        a[index + 1] = unsort;
    }

下面一种代码实现:

    private static void insertSort(int[] a){
        int temp,i,j;
        for (i = 1; i < a.length; i++) {
            if(a[i] < a[i-1]){
                temp = a[i];
                for (j = i-1; j >= 0 && temp < a[j]; j--) {
                    a[j+1] = a[j];
                }
                a[j+1] = temp;
            }
        }
    }

你可能感兴趣的:(排序算法之直接插入排序)