Thread: Recursion help
View Single Post
Join Date: Dec 2008
Posts: 53
Reputation: neilcoffey will become famous soon enough neilcoffey will become famous soon enough 
Solved Threads: 6
neilcoffey neilcoffey is offline Offline
Junior Poster in Training

Re: Recursion help

 
0
  #7
Dec 15th, 2008
On average, you really wouldn't expect to perform so many recursions as to get a stack overflow error: even with your list size of 16,000, on average, you'd expect to go to around 14 or so levels of recursion (2^14 = 16384).

But in the WORST case, quicksort will require 'n' levels of recursion, and I think you're hitting this worst case. It looks like you're sorting the data and then always using the rightmost element as the pivot value. If you do that, then if you think about it, on each recursion you're picking the highest value in the sublist as the pivot value, so that instead of splitting the list roughly into two equal halves (on average what you'd expect if you chose a random pivot position), you're splitting it into "halves" that are (n-1) and 1 in length.

To get round this you need to either:
(1) guarantee that you won't pass already-sorted data to your method, or
(2) have a better pivot selection method (common strategies are to just pick a random index each time, or perform "quick heuristic" to choose a pivot value -- e.g. take the average of the numbers at x random indices).
Reply With Quote