排序演算法Java實現(歸併排序)

來源:互聯網
上載者:User

標籤:

 1 package sorting; 2  3 /** 4  * 歸併排序 5  * 平均O(nlogn),最好O(nlogn),最壞O(nlogn);空間複雜度O(n);穩定;較複雜 6  * @author zeng 7  * 8  */ 9 public class GuibingPaixu {10 11     public static void Merge(int[] arr, int startIndex, int midIndex,12             int endIndex) {13         int[] tempArr = new int[arr.length];14         System.out.println("Merge " + startIndex + "~" + endIndex);15         int i = startIndex, j = midIndex + 1, k = startIndex;16         while (i != midIndex + 1 && j != endIndex + 1) {17             if (arr[i] > arr[j])18                 tempArr[k++] = arr[i++];19             else20                 tempArr[k++] = arr[j++];21         }22         while (i != midIndex + 1)23             tempArr[k++] = arr[i++];24         while (j != endIndex + 1)25             tempArr[k++] = arr[j++];26         for (i = startIndex; i <= endIndex; i++)27             arr[i] = tempArr[i];28         for (int p : arr)29             System.out.print(p + " ");30         System.out.println();31     }32 33     static void MergeSort(int[] arr, int startIndex, int endIndex) {34         int midIndex;35         if (startIndex < endIndex) {36             midIndex = (startIndex + endIndex) / 2;37             MergeSort(arr, startIndex, midIndex);// 左邊有序38             MergeSort(arr, midIndex + 1, endIndex);// 右邊有序39             Merge(arr, startIndex, midIndex, endIndex);40         }41     }42 43     public static void main(String[] args) {44         int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };45         MergeSort(b, 0, b.length - 1);46         for (int i : b)47             System.out.print(i + " ");48 49     }50 }

 

排序演算法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.