冒泡排序及其优化的 Java 实现

冒泡排序,时间复杂度为 N2 ,每次交换相邻的不同大小的数,每趟排序使最大的数沉到最后(如果从小到大排序)

public class BubbleSort
{
	public void Sort(int a[])
	{
		int i, j, temp;
		for(i = 0 ;i < a.length ; i++ )
		{
			for(j = 0 ; j < a.length - 1 - i ; j++) //每次最大数之前被放到最后,所以只需要遍历到a.length - 1 - i

				if(a[j]>a[j+1])
				{
					temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
				}
			System.out.println("第"+ i + "趟排序的结果为:");
			PrintArray(a);
		}
	}
	
	public void PrintArray(int a[])
	{
		for(int i = 0 ; i <a.length ; i ++)
			System.out.print(a[i] + " ");
		System.out.println();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		BubbleSort bs = new BubbleSort();
		int a[] = {5,1,11,3,7,3,6,8,2,10};
		bs.PrintArray(a);
		bs.Sort(a);		
	}

}

5 1 11 3 7 3 6 8 2 10 
第0趟排序的结果为:
1 5 3 7 3 6 8 2 10 11 
第1趟排序的结果为:
1 3 5 3 6 7 2 8 10 11 
第2趟排序的结果为:
1 3 3 5 6 2 7 8 10 11 
第3趟排序的结果为:
1 3 3 5 2 6 7 8 10 11 
第4趟排序的结果为:
1 3 3 2 5 6 7 8 10 11 
第5趟排序的结果为:
1 3 2 3 5 6 7 8 10 11 
第6趟排序的结果为:
1 2 3 3 5 6 7 8 10 11 
第7趟排序的结果为:
1 2 3 3 5 6 7 8 10 11 
第8趟排序的结果为:
1 2 3 3 5 6 7 8 10 11 
第9趟排序的结果为:
1 2 3 3 5 6 7 8 10 11 

优化1:如果某次遍历已经没有数据交换,说明整个数组已经有序

public void Sort(int a[])
	{
		int i = 0, j, temp;
		boolean flag = true;
		while(flag)
		{			
				flag = false;
				for(j = 0 ; j < a.length - 1 - i ; j++)
					if(a[j]>a[j+1])
					{
						flag = true;
						temp = a[j];
						a[j] = a[j+1];
						a[j+1] = temp;
					}
				System.out.println("第"+ i++ + "趟排序的结果为:");
				PrintArray(a);
			}
		
	}
5 1 11 3 7 3 6 8 2 10 
第0趟排序的结果为:
1 5 3 7 3 6 8 2 10 11 
第1趟排序的结果为:
1 3 5 3 6 7 2 8 10 11 
第2趟排序的结果为:
1 3 3 5 6 2 7 8 10 11 
第3趟排序的结果为:
1 3 3 5 2 6 7 8 10 11 
第4趟排序的结果为:
1 3 3 2 5 6 7 8 10 11 
第5趟排序的结果为:
1 3 2 3 5 6 7 8 10 11 
第6趟排序的结果为:
1 2 3 3 5 6 7 8 10 11 
第7趟排序的结果为:
1 2 3 3 5 6 7 8 10 11 

优化2:每次记住最后发生交换的位置,下次循环只需要遍历到这个位置(如有100个数,后90个数已经有序且都大于前面的数字)

public void Sort(int a[])
	{
		int i = 0, j, k, temp;
		int flag = a.length - 1;
		while (flag > 0)
		{
			k = flag;
			flag = 0;
			for (j = 0; j < k; j++)
				if (a[j] > a[j + 1])
				{
					flag = j;
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
			System.out.println("第" + i++ + "趟排序的结果为:");
			PrintArray(a);
		}


	}


在a[] = {5,1,6,7,8,9,10,11,12,13}时,排序过程为 


5 1 6 7 8 9 10 11 12 13 
第0趟排序的结果为:
1 5 6 7 8 9 10 11 12 13 

猜你喜欢

转载自blog.csdn.net/zhouy1989/article/details/25051211