mergesort

rbl8hiat  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(366)

我正在浏览下面的示例程序,试图理解下面的递归是如何工作的,我无法理解左数组元素和右数组元素是如何排序的,最后合并了两个子数组,如下所示。以下方法的任何图示解释都会有很大帮助,因为我试图理解下面的递归代码。

  1. public static int[] mergeSort(int[] arrayToSort) {
  2. // BASE CASE: arrays with fewer than 2 elements are sorted
  3. if (arrayToSort.length < 2) {
  4. return arrayToSort;
  5. }
  6. // STEP 1: divide the array in half
  7. // we use integer division, so we'll never get a "half index"
  8. int midIndex = arrayToSort.length / 2;
  9. int[] left = Arrays.copyOfRange(arrayToSort, 0, midIndex);
  10. int[] right = Arrays.copyOfRange(arrayToSort, midIndex, arrayToSort.length);
  11. // STEP 2: sort each half
  12. int[] sortedLeft = mergeSort(left);
  13. int[] sortedRight = mergeSort(right);
  14. // STEP 3: merge the sorted halves
  15. int[] sortedArray = new int[arrayToSort.length];
  16. int currentLeftIndex = 0;
  17. int currentRightIndex = 0;
  18. for (int currentSortedIndex = 0; currentSortedIndex < arrayToSort.length;
  19. currentSortedIndex++) {
  20. // sortedLeft's first element comes next
  21. // if it's less than sortedRight's first
  22. // element or if sortedRight is exhausted
  23. if (currentLeftIndex < sortedLeft.length
  24. && (currentRightIndex >= sortedRight.length
  25. || sortedLeft[currentLeftIndex] < sortedRight[currentRightIndex])) {
  26. sortedArray[currentSortedIndex] = sortedLeft[currentLeftIndex];
  27. currentLeftIndex++;
  28. } else {
  29. sortedArray[currentSortedIndex] = sortedRight[currentRightIndex];
  30. currentRightIndex++;
  31. }
  32. }
  33. return sortedArray;
  34. }
fbcarpbf

fbcarpbf1#

排序在合并循环中执行:
如果数组非常小(0或1个元素), mergeSort() 立即归还。
否则,它会将阵列分成两个大小大致相同的子阵列, left 以及 right ,通过递归调用相同的方法进行排序:

  1. // STEP 2: sort each half
  2. int[] sortedLeft = mergeSort(left);
  3. int[] sortedRight = mergeSort(right);

最后一步遍历已排序的半部分以生成新的已排序数组。
递归调用之所以完成,是因为它们只使用严格小于参数数组的子数组执行。

相关问题