Java与算法之(9) - 直接插入排序

版权声明:欢迎转载, 转载请保留原文链接。 https://blog.csdn.net/autfish/article/details/52585106

直接插入排序是最简单的排序算法,也比较符合人的思维习惯。想像一下玩扑克牌抓牌的过程。第一张抓到5,放在手里;第二张抓到3,习惯性的会把它放在5的前面;第三张抓到7,放在5的后面;第四张抓到4,那么我们会把它放在3和5的中间。


直接插入排序正是这种思路,每次取一个数,从前向后找,找到合适的位置就插进去。

代码也非常简单:

/**
 * 直接插入排序法
 * Created by autfish on 2016/9/18.
 */
public class InsertSort {
    private int[] numbers;

    public InsertSort(int[] numbers) {
        this.numbers = numbers;
    }

    public void sort() {
        int temp;
        for(int i = 1; i < this.numbers.length; i++) {
            temp = this.numbers[i]; //取出一个未排序的数
            for(int j = i - 1; j >= 0 && temp < this.numbers[j]; j--) {
                this.numbers[j + 1] = this.numbers[j];
                this.numbers[j] = temp;
            }
        }
        System.out.print("排序后: ");
        for(int x = 0; x < numbers.length; x++) {
            System.out.print(numbers[x] + "  ");
        }
    }

    public static void main(String[] args) {
        int[] numbers = new int[] { 4, 3, 6, 2, 7, 1, 5 };
        System.out.print("排序前: ");
        for(int x = 0; x < numbers.length; x++) {
            System.out.print(numbers[x] + "  ");
        }
        System.out.println();
        InsertSort is = new InsertSort(numbers);
        is.sort();
    }
}
测试结果:

排序前: 4  3  6  2  7  1  5  
排序后: 1  2  3  4  5  6  7  
直接插入排序的时间复杂度,最好情况是O(n),最坏是O(n^2),平均O(n^2)。

猜你喜欢

转载自blog.csdn.net/autfish/article/details/52585106