[英]Quicksort - Java
我正在实施快速排序,但答案显示不正确。 我一直在寻找错误,但不知道我哪里出错了。 答案仍然是 3,5,1,8,6,7,9,2。 有人可以告诉我我的代码有什么问题吗?
public class quicksortJava {
public static void main (String args[]) {
int A [] = {3,5,1,8,6,7,9,2};
quicksort(A,0,A.length-1);
for(int i = 0; i < A.length; i++ ){
System.out.print(A[i]+" ");
}
}
public static void quicksort(int[]A,int start,int end){
if (start < end){
int pIndex = partition(A,start,end);
quicksort(A,start,pIndex-1);
quicksort(A,pIndex+1,end);
}
}
public static int partition(int[]A,int start,int end){
int pivot = A[end];
int pIndex = start;
for (int i = start;i < end; i++){
if (A[i] <= pivot){
swap(A[i],A[pIndex]);
pIndex++;
}
}
swap(A[pIndex],A[end]);
return pIndex;
}
public static void swap(int A,int B){
int temp = A;
A = B;
B = temp;
}
您的交换方法不起作用,因为您只是在“交换”方法中更改局部变量“A”和“B”。 您实际上并没有更改列表中的任何内容。
尝试这个:
public static void swap(int a, int b) {
int tmp = list[a];
list[a] = list[b];
list[b] = tmp;
}
您还需要将所有调用更改为“swap”,以便它们传递索引而不是值。
(此外,Java 变量是小写/驼峰式,而不是大写。您有多个名为“A”的变量,这会让一切变得混乱。)
这里是正确答案
public static int partition(int[]A,int start,int end){
int pivot = A[end];
int pIndex = start;
for (int i = start;i < end; i++){
if (A[i] <= pivot){
//swap(i,pIndex);
int temp = A[i];
A[i] = A[pIndex];
A[pIndex] = temp;
pIndex++;
}
}
//swap(A[pIndex],A[end]);
int temp = A[pIndex];
A[pIndex] = A[end];
A[end] = temp;
return pIndex;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.