0

My friend has a small problem and I'm at the end of my knowledge. He wrote a Simple (he got it in school) QuickSort Algorithm And it produces a StackOverflow Error. I know it means it calls itself recursive too many times somewhere, but I can't get the logical Error - please help me!

Here is the code (I'm leaving out some code as that is only to show it in 2 text areas):

int array [] = new int [10];
...
 public static void quicksort (int array[],int l,int r){
int i = l;
int j = r;
int mitte = array [(l+r)/2];

while (i<j) {
  while  (array[i]<mitte) {
    i++;
  } // end of if
  while  (mitte<array[i]) {
    j--;
  } // end of if
  if (i<=j) {
    int merke =array[i];
    array[i] = array [j];
    array [j] = merke ;
    i++;
    j--;
  } // end of if
  if (i<j) {
    quicksort(array,l,j);
  } // end of if
  if (l<r) {
    quicksort(array,l,r);
  } // end of if
} // end of while
}

It is called like this:

 quicksort(array,0,9);

But, if We call it and the 2 numbers are the same, it gives no Overflow.

If more code is needed, here is the full Code on pastebin: http://pastebin.com/cwvbwXEu

3 Answers 3

1

First, you have an infinite loop here:

while  (mitte<array[i]) {
    j--;
  } // end of if

It needs to be array[j]

Secondly (and leading to the infinite recursion), in the second call to quicksort

if (l<r) {
  quicksort(array,l,r);
} // end of if

In recursion, you always need to shorten the range that you call yourself with, or else it'll be infinite. I haven't worked out exactly what you're doing, but I think you mean:

if (i<r) {
   quicksort(array,i,r);
 } // end of if
Sign up to request clarification or add additional context in comments.

2 Comments

It seems like it was a simple copying from board mistake by my friend. Thanks man.
Note also that the recursion shouldn't be inside the while loop. Quicksort is (1) separate the array into two groups, one all below your "pivot" middle number and one all above, then (2) sort each groups with a single call to quicksort on each.
1

This call:

if (l<r) {
  quicksort(array,l,r);
}

recursively calls quicksort with the same arguments that were passed in, rather than calling with a smaller subproblem to solve. It will therefore infinitely recurse.

Comments

1
if (l<r) 
quicksort(array,l,r);

Isnt l always less than r? this will cause an infinite recursion which is why you dont get an overflow if both values are the same.

1 Comment

doh of course! Sorry for my dumbness XD - thanks for the quick help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.