快速排序不起作用
Quick sorting is not working
我没有任何编译错误,但它仍然无法正常工作。我认为这与数组边界有关,但我无法修复它。我尝试更改它们但仍然无法正常工作。
这是我的代码:
public class QuickSort {
public static void main(String[] args) {
int[] A = new int[] {6,2,7,8,1};
quickSort(A,0,A.length-1);
printArray(A);
}
public static void quickSort(int[] A,int P,int r){
int Q = partition(A,P,r);
if (P < Q-1){
quickSort(A,P,Q-1);
}
if (Q < r){
quickSort(A,Q,r);
}
}
public static int partition(int[] A,int P, int r){
int i = P; //left
int j = r; //right
int pivot = A[(P+r)/2];
int temp;
while (i <= j){
while (pivot > A[i]){
i++;
}
while (pivot < A[j]){
j--;
}
if (i <= j){
temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
j--;
}
}
return j;
}
public static void printArray(int[] A){
for (int i = 0; i < A.length;i++){
System.out.println(A[i]);
}
}
}
参数P为开始,r为结束。我从中间选择支点
- 你的命名很不直观。坚持命名约定可以让您的代码更容易被其他人理解。
- 在分区 return 中而不是 j。
- 使用递归时必须确保它结束。你继续用无意义的边界处理你的数组,以防万一 (r-P<2)!
将这样的 return 语句插入到您的快速排序方法中
代码:
public static void quickSort(int[] A,int l,int r) {
if ((r-l)<2) return; //end recursion when there is just one or less elements to sort
int p = partition(A,l,r);
if (l < p-1) { quickSort(A,l,p-1); }
if (p < r) { quickSort(A,p,r); }
}
我没有任何编译错误,但它仍然无法正常工作。我认为这与数组边界有关,但我无法修复它。我尝试更改它们但仍然无法正常工作。
这是我的代码:
public class QuickSort {
public static void main(String[] args) {
int[] A = new int[] {6,2,7,8,1};
quickSort(A,0,A.length-1);
printArray(A);
}
public static void quickSort(int[] A,int P,int r){
int Q = partition(A,P,r);
if (P < Q-1){
quickSort(A,P,Q-1);
}
if (Q < r){
quickSort(A,Q,r);
}
}
public static int partition(int[] A,int P, int r){
int i = P; //left
int j = r; //right
int pivot = A[(P+r)/2];
int temp;
while (i <= j){
while (pivot > A[i]){
i++;
}
while (pivot < A[j]){
j--;
}
if (i <= j){
temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
j--;
}
}
return j;
}
public static void printArray(int[] A){
for (int i = 0; i < A.length;i++){
System.out.println(A[i]);
}
}
}
参数P为开始,r为结束。我从中间选择支点
- 你的命名很不直观。坚持命名约定可以让您的代码更容易被其他人理解。
- 在分区 return 中而不是 j。
- 使用递归时必须确保它结束。你继续用无意义的边界处理你的数组,以防万一 (r-P<2)! 将这样的 return 语句插入到您的快速排序方法中
代码:
public static void quickSort(int[] A,int l,int r) {
if ((r-l)<2) return; //end recursion when there is just one or less elements to sort
int p = partition(A,l,r);
if (l < p-1) { quickSort(A,l,p-1); }
if (p < r) { quickSort(A,p,r); }
}