我写了快速排序代码,如下所示。排序采用中间数作为支点:
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] numbers = {3, 6, 9, 1, 34};
int low = 0;
int high = numbers.length - 1;
quicksort(numbers, low, high);
}
static void quicksort(int[] arr, int low, int high) {
int i = low;
int j = high;
int middle = arr[(low + high) / 2];
while(i < j) {
while(arr[i] < middle ) {
i++;
}
while(arr[j] > middle) {
j--;
}
if( i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
if(low < j) {
quicksort(arr, low, j);
}
if(i < high) {
quicksort(arr, i, high);
}
System.out.println(Arrays.toString(arr));
}
}
但是,运行代码后我得到stackoverflow异常。 它表示线程中的异常&#34; main&#34; java.lang.StackOverflowError的
Exception in thread "main" java.lang.StackOverflowError
at QuickSort.quicksort(QuickSort.java:47)
at QuickSort.quicksort(QuickSort.java:47)
at QuickSort.quicksort(QuickSort.java:47)
at QuickSort.quicksort(QuickSort.java:47)
at QuickSort.quicksort(QuickSort.java:47)
at QuickSort.quicksort(QuickSort.java:47)
at QuickSort.quicksort(QuickSort.java:47)
请帮我找出运行上述代码可能出现的问题。
答案 0 :(得分:3)
i和j的值需要分别递增和递减。请参阅下面的工作代码:
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] numbers = {3, 9, 6, 1, 34};
int low = 0;
int high = numbers.length - 1;
quicksort(numbers, low, high);
}
static void quicksort(int[] arr, int low, int high) {
int i = low;
int j = high;
int middle = arr[(low + high) / 2];
while(i <= j) {
while(arr[i] < middle ) {
i++;
}
while(arr[j] > middle) {
j--;
}
if( i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if(low < j) {
quicksort(arr, low, j);
}
if(i < high) {
quicksort(arr, i, high);
}
System.out.println(Arrays.toString(arr));
}
}
希望这有帮助!
答案 1 :(得分:0)
您可以查看此link以更好地了解快速排序及其工作原理。
public static void quickSort(int [] arr,int low,int high){ if(arr == null || arr.length == 0) 返回;
if (low >= high)
return;
int middle = low + (high - low) / 2;
int pivot = arr[middle];
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}