2013-11-03 62 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

你可以做到這一點。 –

相關問題