我想使用快速排序按特定列对二维数组进行排序。我已经能够为一维数组实现快速排序。
public class QuickSort1D {
public static void main(String[] args) {
int[] A = {9, 3, 10, 4, 1, 44, 12, 2, 90, 0};
int l = 0;
int r = A.length-1;
QuickSort(A, l, r);
for (int i = 0; i < A.length; i++){
System.out.print(A[i] + " ");
}
}
private static void QuickSort(int[] a, int l, int r) {
int i;
if (r > l){
i = partition(a, l, r);
QuickSort(a, l, i-1);
QuickSort(a, i+1, r);
}
}
private static int partition(int[] a, int l, int r) {
int v = a[r];
int i = l;
int j = r;
int temp;
while (i < j){
while (a[i] < v){
i = i + 1;
}
while ((i < j) && (a[j] >= v)){
j = j - 1;
}
temp = a[i];
if (i < j){
a[i] = a[j];
a[j] = temp;
}else{
a[i] = a[r];
a[r] = temp;
}
}
return i;
}
}
为此,对于二维数组,我将必须在QuickSort方法中包括用于指定列的参数。我不知道如何从那里继续。
例如,数组最初是
{{4, 1, 3},
{6, 0, 2},
{5, 9, 8}}
并且按第2列排序的数组应为
{{6, 0, 2},
{4, 1, 3},
{5, 9, 8}}
您int column
在快速排序方法中包含一个参数。
然后,您只需将所有内容替换a[x]
为a[x][column]
,而swap方法(如果使用temp则为if)保持不变。只需将temp设为int[]
,而不是int
。当然,a的类型必须int[][]
是int[]
。
完毕 :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句