標籤:
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實現(歸併排序)