天天看點

雙端冒泡排序

/*
雙端冒泡就是一趟排序同時确定一個最大元素和一個最小元素,那麼
總的排序時間相比傳統的冒泡排序會降低一半左右的時間,結束條件為
當下沉的下限等于上浮的上限。即沒有要上浮的元素也沒有要下沉的元素。此時
排序結束。

時間複雜度為O(n*n/2)向上取整數,但總體的數量級還是在O(n^2)。
*/

public class BubbleSort03
{
	public static void main(String[]args){
		int a[] = {12,5,43,6,2,54,8};
		int i,j,k;

		for(i=0;i<a.length;i++){
			j = 1;
			k = a.length-1;

			while(j<a.length-i-1){
				if(a[j]>a[j+1]){
					int temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
				}
				j++;
			}//while

			while(k>i){
				if(a[k]<a[k-1]){
					int temp = a[k];
					a[k] = a[k-1];
					a[k-1] = temp;
				}
				k--;
			}
			System.out.println("第"+i+"趟排序結果:");
			for(int te=0;te<a.length;te++){
				System.out.print(a[te]+" ");
			}
			if(j == k){
				break;
			}
		}
		
	}//main
}