java歸併排序

來源:互聯網
上載者:User

標籤:

基本排序:歸併(Merge)排序法是將兩個(或兩個以上)有序表合并成一個新的有序表,即把待排序序列分為若干個子序列,每個子序列是有序的。然後再把有序子序列合并為整體有序序列。

 1 public static void main(String[] args){ 2         int a[] = {34, 8, 64, 51, 32, 21}; 3         mergeSort(a, 0, a.length-1); 4         for (int i = 0; i < a.length; i++) { 5             System.out.print(a[i] + " "); 6         } 7     } 8      9     public static void  mergeSort(int[] a, int left, int right) {10         if (left < right) {11             int center = (left+right)/2;12             mergeSort(a, left, center);13             mergeSort(a, center+1, right);14             merge(a, left, center, right);15         }16     }17     18     public static void merge(int[] a, int left, int center, int right) {19         int[] tmpArr = new int[a.length];20         int mid = center+1;21         int third = left;22         int tmp = left;23         24         while (left <= center && mid <= right) {25             if (a[left] <= a[mid]) {26                 tmpArr[third++] = a[left++];27             } else {28                 tmpArr[third++] = a[mid++];29             }30         }31         while (mid <= right) {32             tmpArr[third++] = a[mid++];33         }34         while (left <= center) {35             tmpArr[third++] = a[left++];36         }37         38         while (tmp <= right) {39             a[tmp] = tmpArr[tmp++];40         }41     }

 

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.