![]() |
| ||
| Recursion help I'm working on a quick sort algorithm using recursion but it's throwing a stackOverflowError. Here is the code: public static void quicksort(int [] A){The thing that's puzzling me is there's no problems when I call for it from this piece of code: public class A5Q5 {but a stackOverflowError is thrown when I try to call for it from this one: public class A5Q6 {Any help will be greatly appreciated. |
| ||
| Re: Recursion help I didn't realize that I was using different command line arguments for A5Q5 and A5Q6 until now. So it seems that my code works fine for arrays of smaller lengths (such as 128) but not for arrays of larger sizes, say 16328. |
| ||
| Re: Recursion help make stack profile |
| ||
| Re: Recursion help In quickSortRec(int [] A, int p, int r)You are using array as parameter, which makes Your code most not effectively. Every call cause store whole array on the stack. |
| ||
| Re: Recursion help Alright, thanks for your help. :) |
| ||
| Re: Recursion help > Every call cause store whole array on the stack. No it doesn't. Arrays in Java are objects and when invoking methods with object references, copy of the reference is created and copied to the stack frame which is then pushed onto the call stack [the stack which maintains the state (stack frame) of the currently executing methods]. The actual array still lives in the heap. |
| ||
| Re: Recursion help 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). |
| All times are GMT -4. The time now is 2:40 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC