【数据结构】-直接插入排序、希尔排序Java实现

前端之家收集整理的这篇文章主要介绍了【数据结构】-直接插入排序、希尔排序Java实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

直接插入排序:将一个记录插入到已排好的有序序列中,从而得到新的、记录数加1的有序序列。
稳定性:稳定;
时间复杂度:O(n*n)


希尔排序:先将整个待排记录分成若干子序列分别进行直接插入排序,待整个序列中的记录基本有序时,再对全体记录进行一次直接插入排序。
稳定性:不稳定;
时间复杂度:最好:O(n)–最坏O(n*n)–平均O(n^1.3)


package org.iti.algorithm;

import java.util.Random;

/** * * @author Tailyou * */
public class ArraySort {
    public static void main(String[] args) {
        int[] array = genArray(8);
        System.out.println("排序前:");
        printArray(array);
        // 直接插入排序
        insertSort(array);
        // 希尔排序
        // shellSort(array);
        System.out.println("排序后:");
        printArray(array);
    }

    /** * 产生数组 * * @return */
    public static int[] genArray(int length) {
        Random random = new Random();
        int[] sort = new int[length];
        for (int i = 0; i < length; i++) {
            sort[i] = random.nextInt(50);
        }
        return sort;
    }

    /** * 打印数组 * * @param sort */
    public static void printArray(int[] sort) {
        for (int i = 0; i < sort.length; i++) {
            if (i == sort.length - 1) {
                System.out.println(sort[i]);
            } else {
                System.out.print(sort[i] + ",");
            }
        }
    }

    /** * 直接插入排序:O(n^2) * * @param array */
    public static void insertSort(int[] array) {
        int dk = 1;
        for (int i = dk; i < array.length; ++i) {
            for (int j = i; j >= dk && array[j] < array[j - dk]; j -= dk) {
                int temp = array[j];
                array[j] = array[j - dk];
                array[j - dk] = temp;
            }
            printArray(array);
        }
    }

    /** * 希尔排序 * * @param array */
    public static void shellSort(int[] array) {
        int dk = array.length / 2;
        while (dk >= 1) {
            for (int i = dk; i < array.length; ++i) {
                for (int j = i; j >= dk && array[j] < array[j - dk]; j -= dk) {
                    int temp = array[j];
                    array[j] = array[j - dk];
                    array[j - dk] = temp;
                }
            }
            dk = dk / 2;
        }
    }
}
原文链接:https://www.f2er.com/datastructure/382605.html

猜你在找的数据结构相关文章