快速排序之java實現

來源:互聯網
上載者:User

標籤:演算法   amp   ring   寫代碼   迴圈   color   興趣   注意   start   

據說一般的筆試或面試都會考考排序,今天就試著想自己實現一把,看了原理後,發現沒那麼容易,又去網上找了下,發現評論都說作者的代碼有問題。這更激起了我的興趣。

遂堅持編寫出來並進行了測試,應該沒有問題,如有問題 希望留言評論

快速排序的理論和演算法的評價就不粘貼了,網上一查一大堆,在這隻寫代碼

 1 public class QuickSort { 2     @Test 3     public void sort(){ 4         int[] a = { 5, 8, 6, 2, 7, 9, 1, 7, 3 }; 5         //int[] a = {3, 1, 2, 5, 7, 9, 6, 4, 8}; 6          7         sort(a, 0, a.length-1); 8         System.out.println(Arrays.toString(a)); 9     }10 11     private  void sort(int[] a, int start, int end) {12         int i=start;13         int j=end;14         int key = a[i];15         int tmp;16         while (j > i) {//向左遍曆17             while (j > i && a[j] >=key)18                 j--;19             if (a[j] < key) {20                 tmp = a[j];  //key存在了a[j]中21                 a[j] = a[i];22                 a[i] = tmp;23             }24             while (j > i && a[i] <= key)25                 i++;26             if (a[i] > key) {27                 tmp = a[i];28                 a[i] = a[j];29                 a[j] = tmp;30             }31         }32         if(j<end)sort(a,j+1,end);33         if(i>start)sort(a,start,i-1);34     }35 36 }

說說幾個我覺得注意的問題:

  1. sort()的形參start,end要賦值給i,j.因為我們要通過下標交換數組中的元素。而且最後還要用到start,end。所以不能直接用start,end操作。
  2. 思想無非就是以start為key從右往左遍曆,只要出現了小於key的元素,即交換;而後從左往右遍曆,大於key的元素交換
  3. 注意交換的過程中,要想明白,key是在不停的變換位置。
  4. 最後i,j應該相等,跳出最外層while迴圈
  5. 而後遞迴調用sort
我遇到的坑,本來自己打算試一下123456789的,結果數組中打了兩個7,出現了死迴圈,後來發現23行沒有寫成>=(30行沒有寫成<=).希望初學的讀者能想明白為什麼要加等號~

 

快速排序之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.