合并到位排序

问题描述

我正在研究一种“合并排序”方法,该方法可以在不分配额外内存的情况下就地对元素进行排序。但是,它目前无法正常运行,我想知道是否有人可以帮助我,因为据我了解,这是一个相对简单的操作。预先谢谢你。

我的合并排序方法

      RegisterClass[] runMergeSort()
  {
     RegisterClass[] mergeSorted = new RegisterClass[capacity];
     
     for (int counter = 0; counter < size; counter++)
        {
           mergeSorted[counter] = registerarray[counter];
        }
     
     runMergeSortHelper(mergeSorted,size - 1);
     
     return mergeSorted;
  }

我的助手方法,它使用递归:

      private void runMergeSortHelper(RegisterClass[] workingArray,int lowIndex,int highIndex)
  {
     int midindex = (lowIndex + highIndex) / 2;
     
     if (lowIndex < highIndex)
        {
           
           runMergeSortHelper(workingArray,lowIndex,midindex);
           runMergeSortHelper(workingArray,midindex+1,highIndex);
                          
           runMerge(workingArray,midindex,highIndex);
        }
              

  }

最后,我的Merge方法应该将所有内容整理好,但是,它只能部分执行此操作。

      private void runMerge(RegisterClass[] workingArray,int midindex,int highIndex)
  {
     int counterJay = midindex;
     int counteraye = lowIndex;
     int counterKay = lowIndex - 1;
              
     while (counteraye < midindex && counterJay <= highIndex)
        {
           counterKay++;
           
           if (workingArray[counteraye].compareto(workingArray[counterJay]) <= -1)
              {
                 counteraye++;
              }
           
           else
              {
                 swapValues(workingArray,counteraye,counterJay);
                 counterJay++;
                 counteraye++;
              }
           
        }
     
     while (counteraye < midindex)
        {
           counterKay++;
           swapValues(workingArray,counterKay);
           counteraye++;
        }
     
     while (counterJay <= highIndex)
        {
           counterKay++;
           swapValues(workingArray,counterJay,counterKay);
           counterJay++;
        }
  }

任何建议都将不胜感激。我在网上看过,但似乎无济于事。请不要让我参考不是就地解决方案的解决方案。

解决方法

交换不适合合并功能使用的逻辑。当发生交换时,从左侧交换到右侧的元素现在会乱序,并且将小于(或等于)左侧所有剩余元素。

每当发现右侧的元素小于左侧的元素时,都需要向右旋转数组的该部分以将右侧的元素放置到位。


无需诉诸更复杂的实现,可以通过在右侧扫描 k =前导元素的数量少于左侧当前元素的数量,然后进行旋转来进行小的优化通过 k 元素。对于随机数据,这无济于事,但对于反向排序的数据,则有很大帮助。