码迷,mamicode.com
首页 > 其他好文 > 详细

插入排序

时间:2014-05-17 14:27:04      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   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
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

插入排序

标签:style   blog   class   code   c   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!