插入排序

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;

 

posted @ 2014-05-15 21:16  owen-beta  阅读(156)  评论(0编辑  收藏  举报