如何进行自下而上合并排序工作

时间:2014-04-19 19:38:48

标签: java sorting mergesort iteration non-recursive

我正在尝试进行迭代自下而上的合并排序,这不会浪费额外的时间将数据从temp复制回原始数组。相反,我想在最后复制一次。这是我到目前为止的代码。但是我不知道如何处理不是两个因素的数组。有人可以给我一个如何做到这一点的建议。谢谢

public static void sort(double[] a) {
double[] tmp= new double[ a.length]
  int width;

  for ( width = 1; width < a.length; width = 2*width )
  {
     // Combine sections of array a of width "width"
 int i;

 for ( i = 0; i < a.length; i = i + 2*width )
 {
        int left, middle, right;

        left = i;
        middle = i + width;
        right  = i + 2*width;

        merge( a, left, middle, right, tmp );

 }

     /* ========================================================
    Instead of doing multiply copy operations inside merge()
        i want to perform ONE copy operation after ALL mereg operations
        ======================================================== */     
 for ( i = 0; i < a.length; i++ )
        a[i] = tmp[i];
  }
}

public static void merge(double[] a,int iLeft, int iMiddle, int iRight, double[] tmp)
{
  int i, j, k;

  i = iLeft;
  j = iMiddle;
  k = iLeft;

  while ( i < iMiddle || j < iRight )
  {
     if ( i < iMiddle && j < iRight )
 {  // Both array have elements
        if ( a[i] < a[j] )
       tmp[k++] = a[i++];
        else
           tmp[k++] = a[j++];
 }
     else if ( i == iMiddle )
        tmp[k++] = a[j++];     // a is empty
 else if ( j == iRight )
        tmp[k++] = a[i++];     // b is empty
  }

  // Copy step is removed !

}

0 个答案:

没有答案