1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| public class MergeSortTest { public static void main(String[] args){ int[] data = new int[]{5, 3, 6, 2, 1, 9, 4, 8, 7}; print(data); mergeSort(data); System.out.println("排序后的数组"); print(data); } public static void mergeSort(int[] data){ sort(data,0,data.length-1); } public void sort(int[] data, int left, int right){ if(left>=right){ return; } int center = (left + right)/2; sort(data,left,center); sort(data, center+1, right); merge(data, left, center, right); print(data); }
public static void merge(int[] data, int left, int center, int right) { int[] tmpArr = new int[data.length]; int mid = center + 1; int third = left; int tmp = left; while(left <= center && mid <= right){ if(data[left] <= data[mid]){ tmpArr[third++] = data[left++]; }else { tempArr[third++] = data[mid++]; } } while(mid <=right){ tmpArr[third++] = data[mid++]; } while(left <= center){ temArr[third++] = data[left++]; } while(tmp <= right){ data[tmp] = tempArr[tmp++]; } } public static void print(int[] data){ for(int i = 0 ; i < data.length; i++){ System.out.print(data[i] + "\t"); } System.out.println(); }
}
|