Having some problems implementing quicksort in java. I get a stackoverflow error when I run this program and I\'m not exactly sure why. If anyone can point out the error, it
First you should fix the bounds of the qsort recursive call as suggested by Keith, since otherwise you're always sorting the whole array over and over again. The you must adjust your partition loop: j is an index, going from the beginning of the subarray to the end of it (including the last element). So you must loop from si + 1 to ei (including ei).
So this is the corrected code. I ran a few test cases and it seems to sort just fine.
public static void qsort(int[] a, int si, int ei){
//base case
if(ei<=si || si>=ei){}
else{
int pivot = a[si];
int i = si+1; int tmp;
//partition array
for(int j = si+1; j<= ei; j++){
if(pivot > a[j]){
tmp = a[j];
a[j] = a[i];
a[i] = tmp;
i++;
}
}
//put pivot in right position
a[si] = a[i-1];
a[i-1] = pivot;
//call qsort on right and left sides of pivot
qsort(a, si, i-2);
qsort(a, i, ei);
}
}
You can try this:
public void sort(int[] A) {
if (A == null || A.length == 0)
return;
quicksort(A, 0, A.length - 1);
}
public void quicksort(int[] A, int left, int right) {
int pivot = A[left + (right - left) / 2];
int i = left;
int j = right;
while (i <= j) {
while (A[i] < pivot) {
i++;
}
while (A[j] > pivot) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if(left < j)
quicksort(A,left,j);
if(i < right)
quicksort(A,i,right);
}
public void exchange(int i, int j){
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
public String toString() {
String s = "";
s += "[" + A[0];
for (int i = 1; i < A.length; i++) {
s += ", " + A[i];
}
s += "]";
return s;
}
Source: Code 2 Learn: Quick Sort Algorithm Tutorial
import java.util.Arrays;
public class QuickSort {
public static int pivot(int[] a, int lo, int hi){
int mid = (lo+hi)/2;
int pivot = a[lo] + a[hi] + a[mid] - Math.min(Math.min(a[lo], a[hi]), a[mid]) - Math.max(Math.max(a[lo], a[hi]), a[mid]);
if(pivot == a[lo])
return lo;
else if(pivot == a[hi])
return hi;
return mid;
}
public static int partition(int[] a, int lo, int hi){
int k = pivot(a, lo, hi);
//System.out.println(k);
swap(a, lo, k);
//System.out.println(a);
int j = hi + 1;
int i = lo;
while(true){
while(a[lo] < a[--j])
if(j==lo) break;
while(a[++i] < a[lo])
if(i==hi) break;
if(i >= j) break;
swap(a, i, j);
}
swap(a, lo, j);
return j;
}
public static void sort(int[] a, int lo, int hi){
if(hi<=lo) return;
int p = partition(a, lo, hi);
sort(a, lo, p-1);
sort(a, p+1, hi);
}
public static void swap(int[] a, int b, int c){
int swap = a[b];
a[b] = a[c];
a[c] = swap;
}
public static void sort(int[] a){
sort(a, 0, a.length - 1);
System.out.print(Arrays.toString(a));
}
public static void main(String[] args) {
int[] arr = {5,8,6,4,2,9,7,5,9,4,7,6,2,8,7,5,6};
sort(arr);
}
}
Try this. It will work for sure.