標籤:證明 -- oid code 否則 system 選擇排序 test png
前言:關於冒泡排序和選擇排序,每次寫的時候都要再看看他們的概念,這次,就自己寫明白1.冒泡排序:
其實冒泡排序應該用例子證明,設數組長度為N。
1.比較相鄰的前後二個資料,如果前面資料大於後面的資料,就將二個資料交換。
2.這樣對數組的第0個資料到N-1個資料進行一次遍曆後,最大的一個資料就“沉”到數組第N-1個位置。
3.N=N-1,如果N不為0就重複前面二步,否則排序完成。
看了基本的方法,就寫個代碼驗證下
1 // 2.冒泡排序 2 @Test 3 public void test2() { 4 int[] arr={14,9,8,15,34,5}; 5 int temp=0; 6 for(int i=0;i<arr.length;i++){ 7 for(int j=0;j<arr.length-1;j++){ 8 if(arr[j]>arr[j+1]){ 9 temp=arr[j];10 arr[j]=arr[j+1];11 arr[j+1]=temp;12 }13 }14 }15 16 //遍曆輸出有三種輸出方式,可以參考我部落格的3中遍曆輸出的方式17 for(int a:arr){18 System.out.println(a);19 }20 }運行效果:
2.選擇排序:
思想:先在所有序列中先找到最小的,然後放到第一個位置。之後再看剩餘元素中最小的,放到第二個位置……以此類推,就可以完成整個的排序工作了。
代碼:
1 @Test 2 public void test4() { 3 int[] arr = { 14, 9, 8, 90, 34, 5,78 }; 4 int minIndex; 5 int temp; 6 for (int i = 0; i < arr.length-1; i++) { 7 minIndex=i; 8 for (int j = i + 1; j < arr.length; j++) { 9 if (arr[j] < arr[minIndex]) {10 minIndex =j;11 }12 }13 if(minIndex!=i){14 temp=arr[i];15 arr[i]=arr[minIndex];16 arr[minIndex]=temp;17 } 18 }19 for (int i : arr) {20 System.out.println(i);21 }22 23 }運行效果:
冒泡排序與選擇排序(經典版)----java基礎總結