首页 > 其他 > 详细

插入排序

时间:2014-05-17 14:26:44      阅读:354      评论:0      收藏:0      [点我收藏+]
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);
    }
}

  运算过程:

bubuko.com,布布扣
{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;
bubuko.com,布布扣

 

插入排序,布布扣,bubuko.com

插入排序

原文:http://www.cnblogs.com/owenbeta/p/3730885.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!