排序算法之插入排序和希尔排序【Java版】

217 阅读1分钟

引言

本篇是排序算法的第二篇,插入排序和希尔排序。

插入排序

1、算法步骤

  1. 以需要排序的数组中第一位为基准点,从后面顺序选取一个数字,与前面的依次进行比较。
  2. 如果结果小于被比较数字,则将被比较数字后移,并继续与之前的数字比较,直到大于被比数字,然后插入。

2、时间复杂度

平均时间复杂度O(n2n^2),最好情况O(n)

3、算法实现

public class InsertSort {

    public static void main(String[] args) {
        int[] numbers = {12,2,24,30,6,16};
        int[] result = InsertSort.insertSort(numbers);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            stringBuffer.append(result[i] + " ");
        }
        System.out.println(stringBuffer.toString());
    }

    //插入排序算法
    public static int[] insertSort(int[] numbers) {
        //对参数进行拷贝
        int[] needSort = Arrays.copyOf(numbers, numbers.length);
        //从第二位数字开始
        for(int i=1; i<needSort.length; i++){
            //记录需要插入的数字
            int tmp = needSort[i];
            int j = i;
            //依次倒序,与之前排序好的数字进行比较
            while (j > 0 && tmp < needSort[j-1]){
                //小于的话,则将被排序数字后移
                needSort[j] = needSort[j-1];
                //再与前一位比较,依次循环
                j--;
            }
            //如果有移动数字则插入,无改变不操作
            if(j != i){
                needSort[j] = tmp;
            }
        }
        return needSort;
    }
}

希尔排序

希尔排序,是插入排序的一个更高效的改进版。

1、算法步骤

1、对需要排序的数列,按照不同的步长进行分组; 2、对分组的数列进行组内排序; 3、然后继续减小步长,重复1、2操作,当步长为1的时候,排序就完成了。

下图是网上找的,下面的d表示间隔,也叫做增量,相同颜色的是一组: 在这里插入图片描述

2、时间复杂度

平均时间复杂度O(n log n),最好情况O(n log2^2 n)

3、算法实现

public class ShellSort {

    public static void main(String[] args) {
        int[] numbers = {12,2,24,30,6,16};
        int[] result = ShellSort.sort(numbers);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            stringBuffer.append(result[i] + " ");
        }
        System.out.println(stringBuffer.toString());
    }


    public static int[] sort(int[] numbers) {
        //对参数进行拷贝
        int[] needSort = Arrays.copyOf(numbers, numbers.length);

        int d = 1;
        while (d < needSort.length){
            //增量的计算公式
            d = d * 3 + 1;
        }
        while (d > 0) {
            for (int i = d; i < needSort.length; i++) {
                int tmp = needSort[i];
                int j = i - d;
                while (j >= 0 && needSort[j] > tmp) {
                    needSort[j + d] = needSort[j];
                    j -= d;
                }
                needSort[j + d] = tmp;
            }
            d = (int) Math.floor(d / 3);
        }
        return needSort;
    }
}

结束语

下一篇:将介绍排序算法之归并排序