Android开发经验谈程序员

一个Java小白通向数据结构算法之旅(6) - 插入排序

2017-11-09  本文已影响0人  cmazxiaoma

前言

过几天就是双11了,现在的我已经没有任何购物的欲望了。也许会在双11,买几本书,充实一下自己,仅此而已。

timg.jpg

插入排序的优点

在一般情况下,插入排序是基本排序算法中最好的一种。虽然插入排序算法需要O(N^2)的时间,但是一般情况下,它要比冒泡排序快一倍,比选择排序还要快一些。

提取思想


手写代码

public class InsertSortDemo {

    public static int[] a = { 11, 20, 5, 4, 8, 14, 2, 10, 20, 9 };

    public static void main(String[] args) {
        // commonInsertSort();
        binaryInsertSort();
        display();
    }

    // 普通插入
    public static void commonInsertSort() {
        int count = a.length;

        for (int i = 0; i < count; i++) {
            int value = a[i];
            int j = i - 1;

            while (j >= 0 && a[j] > value) {
                a[j + 1] = a[j];
                j--;
            }

            a[j + 1] = value;
        }
    }

    // 二分法插入
    public static void binaryInsertSort() {
        int count = a.length;
        int insertValue;

        for (int i = 0; i < count; i++) {
            int start = 0;
            int end = i - 1;
            int mid;
            insertValue = a[i];

            while (start <= end) {
                mid = start + (end - start) / 2;

                if (insertValue > a[mid]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }

            for (int k = i; k > start; k--) {
                a[k] = a[k - 1];
            }

            a[start] = insertValue;
        }
    }

    public static void display() {
        int count = a.length;

        for (int i = 0; i < count; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println("");
    }
}

插入排序的效率


尾言

最近养着了白天睡觉,晚上写代码的习惯,于是乎成了一只特立独行的猪了。生活作息不规律,这是病,该治一治了。还是那一句话,勿以善小而不为。

上一篇 下一篇

猜你喜欢

热点阅读