I have written quick sort code as below. The sort takes middle number as pivot:
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));
}
}
However, after running the code i am getting stackoverflow exception. It says Exception in thread "main" 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)
Please help me find out what might be wrong in running the above code.
The value of i and j needs to be incremented and decremented respectively. Please see below the working code:
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));
}
}
Hope this helps!
You can look at this link for better understanding of quick sort,how its work.
public static void quickSort(int[] arr, int low, int high) { if (arr == null || arr.length == 0) return;
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);
}
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.