class MergeSort implements SortStrategy ...{ private Comparable[] bridge; /** *//** *利用归并排序算法对数组obj进行排序 */ publicvoid sort(Comparable[] obj) ...{ if (obj ==null) ...{ thrownew NullPointerException("The param can not be null!"); } bridge =new Comparable[obj.length]; //初始化中间数组 mergeSort(obj, 0, obj.length -1); //归并排序 bridge =null; } /** *//** *将下标从left到right的数组进行归并排序 *@param obj 要排序的数组的句柄 *@param left 要排序的数组的第一个元素下标 *@param right 要排序的数组的最后一个元素的下标 */ privatevoid mergeSort(Comparable[] obj, int left, int right) ...{ if (left < right) ...{ int center = (left + right)/2; mergeSort(obj, left, center); mergeSort(obj, center +1, right); merge(obj, left, center, right); } } /** *//** *将两个对象数组进行归并,并使归并后为升序。归并前两个数组分别有序 *@param obj 对象数组的句柄 *@param left 左数组的第一个元素的下标 *@param center 左数组的最后一个元素的下标 *@param right 右数组的最后一个元素的下标 */ privatevoid merge(Comparable[] obj, int left, int center, int right) ...{ int mid = center +1; int third = left; int tmp = left; while (left <= center && mid <= right) ...{ //从两个数组中取出小的放入中间数组 if (obj[left].compareTo(obj[mid]) <=0) ...{ bridge[third++] = obj[left++]; }else bridge[third++] = obj[mid++]; } //剩余部分依次置入中间数组 while (mid <= right) ...{ bridge[third++] = obj[mid++]; } while (left <= center) ...{ bridge[third++] = obj[left++]; } //将中间数组的内容拷贝回原数组 copy(obj, tmp, right); } /** *//** *将中间数组bridge中的内容拷贝到原数组中 *@param obj 原数组的句柄 *@param left 要拷贝的第一个元素的下标 *@param right 要拷贝的最后一个元素的下标 */ privatevoid copy(Comparable[] obj, int left, int right) ...{ while (left <= right) ...{ obj[left] = bridge[left]; left++; } } }
归并算法是分治算法思想的一个应用实例。
The divide-and-conquer paradigm involves three steps at each level of the recursion: • Divide the problem into a number of subproblems. • Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner. • Combine the solutions to the subproblems into the solution for the original problem.
The merge sort algorithm closely follows the divide-and-conquer paradigm. Intuitively, it operates as follows. • Divide: Divide the n-element sequence to be sorted into two subsequences of n/2 elements each. • Conquer: Sort the two subsequences recursively using merge sort. • Combine: Merge the two sorted subsequences to produce the sorted answer.