薛映冰的代码狂躁症

人最痛苦的不是失败,而是我本可以

排序算法第三章 插入排序

| Comments

从现在开始,我会尝试用我自己的话来表达一些算法,如果说得不好,请见谅。

插入排序主要步骤分为以下几部分:
1、从第2个元素开始把元素一个一个拿出来
2、把拿出来的元素从后向前一个一个比较,如果被比较的数大于拿出来的元素,则被比较的数向后移一位
3、当拿出来的元素小于等于被比较数时,把拿出来的元素存入被比较数的下一个位置

以上就是插入排序啦,附上图片一张,并贴上wiki的链接: http://en.wikipedia.org/wiki/Insertion_sort 最后附上一张排序图(图片来自wiki):

InsertionSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class InsertionSort {
    public static void main(String[] args) {
        int[] a = {3,5,2,6,1,8,9,45,23,87,34,65};
        for(int i:a){
            System.out.print(i+" ");
        }
        System.out.println();
        a = new InsertionSort().excute(a);
        for(int i:a){
            System.out.print(i+" ");
        }
    }

    public int[] excute(int[] a){
        for(int i = 1; i < a.length; i++){
            int temp = a[i];
            int j = i;
            while(j > 0 && a[j-1] > temp){
                a[j] = a[j-1];
                j--;
            }
            a[j] = temp;
        }
        return a;
    }
}

Comments