歸併排序實現java
阿新 • • 發佈:2018-12-13
public class Sort { public static void main(String[] args) { int[] arr = {1, 4, 6, 2, 3, 4}; merge(arr,0,arr.length-1); for (int i = 0; i < arr.length; i++) { System.out.print(i + " "); } } private static void merge(int[] arr, int left, int right) { if (left >= right) return; int mid = (left + right)/2; merge(arr,left,mid); merge(arr,mid+1,right); mergeTwo(arr,left,mid,right); } private static void mergeTwo(int[] a, int left, int mid, int right) { int[] tmp = new int[a.length]; int r1 = mid + 1; int tIndex = left; while(left <=mid && r1 <= right) { if (a[left] <= a[r1]) tmp[tIndex++] = a[left++]; else tmp[tIndex++] = a[r1++]; } while (left <=mid) { tmp[tIndex++] = a[left++]; } while ( r1 <= right ) { tmp[tIndex++] = a[r1++]; } } }