2013-11-03 59 views
0

你们能解释一下这个快速排序方法吗?我正在尝试将这些代码实现到我的程序中,但作者没有解释它的功能,或者它是如何实现的。还请注意,我在高中,所以请尽量保持可以理解。有人可以解释这种快速排序方法吗?

我所知道的是它快速排列了一个二维数组。我也知道它使用递归来执行它的快速排序。不幸的是,这就是它。任何帮助,将不胜感激。

public double[][] quicksort(double[][] array, int key, int down, int top) { 
    double[][] a = new double[array.length][2]; 
    System.arraycopy(array, 0, a, 0, a.length); 

    int i = down; 
    int j = top; 
    double x = a[(down + top)/2][key]; 

    do { 
     while (a[i][key] < x) { 
     i++; 
     } 
     while (a[j][key] > x) { 
     j--; 
     } 
     if (i <= j) { 
     double[] temp = new double[a[i].length]; 

     for (int y = 0; y < a[i].length; y++) { 
      temp[y] = a[i][y]; 
      a[i][y] = a[j][y]; 
      a[j][y] = temp[y]; 
     } 
     i++; 
     j--; 
     } 
    } while (i <= j); 

    if (down < j) { 
     a = quicksort(a, key, down, j); 
    } 

    if (i < top) { 
     a = quicksort(a, key, i, top); 
    } 

    return a; 
    } 
} 
+0

严重:[谷歌](https://www.google.com/search?q=quicksort) –

+2

你知道如何快速排序,一般来说,作品? –

+2

这是一个很好的机会来处理你的代码调试技巧。看看它做了什么,在不同的地方打印出一些变量,逐步完成并根据需要添加自己的评论。这样做会让你成为一个更强大的程序员。 – Serdalis

回答

0

几个步骤要知道:

  • array是键 - 值对的阵列,并且它是由键进行排序。

  • 这个quicksort返回原始数组的副本,而不是更改现有的数组。

看评论:

public double[][] quicksort(double[][] array, int key, int down, int top) { 
    //create copy of array (the author wanted to return a new one) 
    double[][] a = new double[array.length][2]; 
    System.arraycopy(array, 0, a, 0, a.length); 

    int i = down; //lower limit 
    int j = top; //upper limit 
    double x = a[(down + top)/2][key]; //the pivot 

    do { 
     while (a[i][key] < x) { //skip over smaller elements in beginning 
     i++; 
     } 
     while (a[j][key] > x) { //skip over larger elements in end 
     j--; 
     } 

     //now do some partitioning 
     if (i <= j) { 
     //create temporary array, for swapping elements 
     double[] temp = new double[a[i].length]; 

     for (int y = 0; y < a[i].length; y++) { 
      temp[y] = a[i][y]; 
      a[i][y] = a[j][y]; 
      a[j][y] = temp[y]; 
     } 
     i++; 
     j--; 
     } 
    } while (i <= j); 

    //if there is a non-empty lower partition, sort that 
    if (down < j) { 
     a = quicksort(a, key, down, j); 
    } 

    //if there is a non-empty upper partition, sort that 
    if (i < top) { 
     a = quicksort(a, key, i, top); 
    } 

    //return the result 
    return a; 
    } 
} 
+0

是这个快速排序工作所必需的System.arraycopy,或者我可以删除它并用'数组'替换'a'? – demiZe

+0

你可以做到这一点。 –

相关问题