【代碼積累-3】bubble sort

public class Test {
	public void test() {
		int test[] = {49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51};
		//int test[] = {5,4,3,2,1};
		
		Bubble bubble = new Bubble();
		bubble.sort(test);
		
		for( int i=0;i<test.length;i++ ) {
			System.out.format("%d ", test[i]);
		}
	}
	
	public class Bubble {
		public void sort(int[] a) {
			/*1、JAVA沒有指針,無法在函數內交換兩個值
			 * 2、冒泡排序的思想就是循環比較相鄰的元素並交換,直到最後一次循環發現沒有交換爲止
			 * 3、冒泡排序算法簡單,效率較低*/
			int i=0;
			int j=0;
			int cnt=0;
			
			do {
				cnt = 0;
				
				for(i=0,j=1;i<a.length-1;i++,j++) {
					if( a[i] > a[j] ) {
						int tmp = a[i];
						a[i] = a[j];
						a[j] = tmp;
						
						cnt++;
					}
				}
			}while(cnt!=0);
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章