首页 > 代码库 > 插入排序

插入排序

?
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
27
28
29
30
31
32
33
34
public class InsertSort
{
    public static void sort(int[] a)
    {
        int N = a.length;
        int count = 0;
        for (int i = 1; i < N; i++)  // 如果只有一个元素, i < N 就不会成立,for循环就不执行
        {
            for (int j = i; j > 0; j--)
            {
                if (a[j] < a[j-1])
                {
                    int temp = 0;
                    temp = a[j];
                    a[j] = a[j-1];
                    a[j-1] = temp;
                    count++;
                }
            }          
        }
         
        for (int i = 0; i < N; i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println("count = " + count);
    }
     
    public static void main(String[] args)
    {
        int[] a = {6, 2, 5, 3, 1, 4};
        InsertSort.sort(a);
    }
}

  运算过程:

{6, 2, 5, 3, 1, 4}
-----------------------------
i = 1; j = 1;
{2, 6, 5, 3, 1, 4}
-----------------------------
i = 2; j = 2;
{2, 5, 6, 3, 1, 4}
j = 1;
-----------------------------
i = 3; j = 3;
{2, 5, 3, 6, 1, 4}
j = 2;
{2, 3, 5, 6, 1, 4}
j = 1;
-----------------------------
i = 4; j = 4;
{2, 3, 5, 1, 6, 4}
j = 3;
{2, 3, 1, 5, 6, 4}
j = 2;
{2, 1, 3, 5, 6, 4}
j = 1;
------------------------------
i = 5; j = 5;
{1, 2, 3, 5, 4, 6}
j = 4;
{1, 2, 3, 4, 5, 6}
j = 3;
j = 2;
j = 1;