合并排序,合并期间重新排列数组。爪哇

时间:2018-10-11 04:44:57

标签: java arrays mergesort

我的合并排序数组遇到了一些麻烦。我遇到的每种情况,合并都可以正常工作,直到遇到递归方法并将先前合并的数组发送回为止。大多数情况下,它会重新排列已经排序的数组,并弄乱了第二个合并方法。例如:(3)(2)(1)(4)->(2,3)(1,4)->(1,3,2,4)将是可能的结果。我在做错什么可能导致这种情况?

public static int[] mergeSort(int[] numbers) {

     if (numbers.length == 1) {
       return numbers; }

     int[] leftSide = new int[numbers.length/2];
     int[] rightSide = new int[numbers.length-leftSide.length];

     System.arraycopy(numbers,0,leftSide,0,leftSide.length);
     System.arraycopy(numbers,leftSide.length,rightSide,0,rightSide.length);

     mergeSort(leftSide);
     mergeSort(rightSide);

     displayArray(leftSide);
     displayArray(rightSide);

     numbers = merge(leftSide,rightSide);

     System.out.println("=============");

     return numbers;
   }  

 public static int[] merge(int[] left, int[] right) {

     int[] temp = new int[left.length+right.length];

     int l = 0;
     int r = 0;
     int t = 0;

     while (l < left.length && r < right.length) {
       if (left[l] > right[r]) {
         temp[t] = right[r];
         r++;
         t++; }
       else {
         temp[t] = left[l];
         l++; 
         t++; }
     }//while

     while (l < left.length) {
       temp[t] = left[l];
         l++;
         t++; }
     while (r < right.length) {
         temp[t] = right[r];
         r++; 
         t++; }

     displayArray(temp);

     return temp;
   }

1 个答案:

答案 0 :(得分:2)

mergeSort函数返回一个排序后的数组,我们不对其进行跟踪。由于已排序的数组(左和右)丢失,合并功能再次拾取未排序的左和右数组。解决方法是更新

mergeSort(leftSide);
mergeSort(rightSide);

leftSide = mergeSort(leftSide);
rightSide = mergeSort(rightSide);

这会将它们更新为各自的排序值