标签:
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 else 20 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 }
标签:
原文地址:http://www.cnblogs.com/zengzhihua/p/4456751.html