冒泡排序與選擇排序(經典版)----java基礎總結

來源:互聯網
上載者:User

標籤:證明   --   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基礎總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.