Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Does anyone have any idea why I would be getting a stack overflow on my quicksort in the following code?:

   private int[] concat( int[] less, int inxl, int pivot, int inxm, int[] more )
   {

      int[] concated = new int[ less.length ];

      for( int inx = 0; inx < inxl; inx++ )
      {

         concated[ inx ] = less[ inx ];

      }

      concated[ inxl ] = pivot;
      inxl++;

      for( int inx = 0; inx < inxm; inx++ )
      {

         concated[ inxl ] = more[ inx ];
         inxl++;

      }      

      return concated;

   }

   private int[] quickSort( int[] array )
   {

      if( array.length <= 1 )
         return array;

      int[] less = new int[ array.length ];
      int[] more = new int[ array.length ];
      int inxl = 0, inxm = 0;

      for( int inx = 1; inx < array.length; inx++ )
      {

         if( array[ inx ] < array[ 0 ] )
         {

            less[ inxl ] = array[ inx ];
            inxl++;

         }
         else
         {

            more[ inxm ] = array[ inx ];
            inxm++;

         }

      }

      return concat( quickSort( less ), inxl, array[ 0 ], inxm, quickSort( more ) );

   }

Any help would be greatly appreciated. I am revising for an interview and been a little rusty so time is of grave importance. Thanks upfront! :)

Sincerely, Piotr.

share|improve this question

2 Answers 2

Your quickSort method's recursion is wrong. It should call itself with smaller arrays (or with some other parameter which gets smaller), not with arrays of the same length. This is why you get an endless recursion, which shows up as a StackOverflowError.

share|improve this answer
    
gotcha! of course... thanks feeling foolish :) –  Piotr May 21 '11 at 18:50
    
i should've used an ArrayList! resizing the less and more arrays is awkward and expansive... unless you have any suggestions? –  Piotr May 21 '11 at 18:52
1  
You could use an additional parameter to the recursive function which says which interval of the array is to be handled. (Then your temporary arrays for the next call need only be maximally this size.) –  Paŭlo Ebermann May 21 '11 at 18:56

I wonder if you're recursing forever. Where do you shrink the array size within your quicksort method? Have you used println's on the array size to debut to see if it's getting smaller?

share|improve this answer
    
I'm a bit slow it seems... 1+ to Paulo for beating me to the punch! :) –  Hovercraft Full Of Eels May 21 '11 at 18:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.