java - Quicksort Stack overflow error -
while practicing exam encountered (for me) strange issue quicksort.
my implementation:
public void quicksort(int l, int r) { if(l<r && l>0 && r<=array.length-1) { int pivot = array[pivot(l, r)]; int = l; int j = r; if(j==i+1) { if(array[i]>array[j]) { system.out.println(array[i]+"<->"+array[j]); int = array[i]; array[i] = array[j]; array[j] = help; } } else{ while(i<=j) { if(array[i]>=pivot && pivot>= array[j]) { system.out.println(array[i]+">="+pivot+">="+array[j]); int = array[i]; array[i] = array[j]; array[j] = help; i++; j--; } else{ i++; } } if(l<j && j<array.length-1)quicksort(l, j); if(i<r)quicksort(i, r); } } }
but giving me "java.lang.stackoverflowerror: null" in (here) line 34. error can, however, avoided swapping j j-1 , j in lines 34 , 35. tried came mind, cannot come solution :/
i think there better implementations of quicksort, here attempt commentary remember better:
public static void quicksort(int[] thearray, int left, int right) { //we declare 2 variables int = left; int j = right; //we calculate pivot, taking middle value of array int pivot = thearray[(left+right)/2]; //check hasn't gone beyond j (i starts @ 0, j starts @ array.length) while(i<=j){ //if here, must mean less-than or equal j, check see if //the array value less our pivot while(thearray[i] < pivot){ //if less-than pivot, value thearray[i] in correct place //so can increment go next i++; } //now same thing j, however, j starts @ array.length, decrement while(thearray[j] > pivot){ j--; } //if here, means need swap values //check hasn't gone beyond j if(i<=j){ //simple swap temp = thearray[i]; thearray[i] = thearray[j]; thearray[j] = temp; //we swapped values, don't need check them again, continue i++; j--; } } //now check if parameter left < j //if left has gone beyond j, means no longer need further sort if(left<j){ //rinse , repeat quicksort(thearray, left, j); //and check still less right parameter }if(i < right){ //rinse , repeat quicksort(thearray, i, right); } }
usage:
//you can amend code don't have pass in array quicksort(thearray, 0, thearray.length-1);
it's simple once understand quicksort trying do. don't stress out it, take 15minute break, watch graphical representation of algorithm , think how code should behave , it's trying achieve. come here, @ code, , start implementing it. rinse , repeat! luck!
also (not sure how exam layout is) mention near-enough guarantee runtime of o(n log n), ought shuffle array before hand.
Comments
Post a Comment