/** * 归并排序 * 进行左右排序,然后归并, * @param numbers * @param low * @param high */ static void mergeSort(int[] numbers,int low,int high){ int mid = (high + low)/2; if (low < high) { //左排序 mergeSort(numbers, low, mid); //右排序 mergeSort(numbers, mid + 1 , high); //归并 merge(numbers, low, mid, high); } }
static void merge(int[] numbers,int low,int mid,int high){ int[] tmp = new int[high - low + 1]; int i = low;//左指针 int j = mid + 1;//右指针 int k = 0; while(i <= mid&&j <= high){ if (numbers[i] < numbers[j]) { tmp[k++] = numbers[i++]; }else { tmp[k++] = numbers[j++]; } } while (i <= mid) { tmp[k++] = numbers[i++]; } while (j <= high) { tmp[k++] = numbers[j++]; } for (int k2 = 0; k2 < tmp.length; k2++) { numbers[k2 + low] = tmp[k2]; } }
原文:http://www.cnblogs.com/phyxis/p/5192918.html