[英]Can someone explain this quicksort method?
你們能解釋一下這種快速排序方法嗎? 我正在嘗試在程序中實現此代碼,但是作者沒有解釋它的作用或作用。 另請注意,我在讀高中,所以請盡量使它易於理解。
我對此的了解是,它可以對二維數組進行快速排序。 我也知道它使用遞歸來執行它的快速排序。 不幸的是,僅此而已。 任何幫助,將不勝感激。
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;
}
}
有幾件事要知道:
array
是鍵值對的數組,並按鍵進行排序。
此快速排序返回原始數組的副本,而不是就地更改現有數組。
看評論:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.