Can you guys please explain this quicksort method? I am trying to implement this code into my program, but the author left no explanation on what it does, or how it does it. Also note that I am in highschool so please try to keep it understandable.
What I DO know about this is that it quicksorts a 2-D array. I also know that it uses recursion to perform its quicksort. Unfortunately, thats it. Any help would be appreciated.
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;
}
}
A couple things to know:
array
is an array of key-value pairs, and it is being sorted by the keys.
This quicksort returns a copy of the original array, instead of changing the existing one in place.
See comments:
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.