| | |
Recursion help
Thread Solved |
•
•
Join Date: Nov 2007
Posts: 22
Reputation:
Solved Threads: 0
I'm working on a quick sort algorithm using recursion but it's throwing a stackOverflowError. Here is the code:
The thing that's puzzling me is there's no problems when I call for it from this piece of code:
but a stackOverflowError is thrown when I try to call for it from this one:
Any help will be greatly appreciated.
Java Syntax (Toggle Plain Text)
public static void quicksort(int [] A){ quickSortRec(A, 0, A.length-1); } public static void quickSortRec(int [] A, int p, int r){ if (p < r){ int q = Partition(A, p, r); quickSortRec(A, p, q-1); quickSortRec(A, q+1, r); } } public static int Partition(int[] A, int p, int r){ int x = A[r]; int i = p-1; int j = p; while (j < r){ if (A[j] <= x){ i++; int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } j++; } int tmp = A[i+1]; A[i+1] = A[r]; A[r] = tmp; return i+1; }
The thing that's puzzling me is there's no problems when I call for it from this piece of code:
Java Syntax (Toggle Plain Text)
public class A5Q5 { public static void main(String[] args){ //Length of array is given by command argument int length = Integer.parseInt(args[0]); //100 arrays of variable lengths of random elements are created and then sorted for (int i=0; i < 100; i++){ int[] arr = new int[length]; for (int j = 0; j < length; j++){ Random rand = new Random(); int n = rand.nextInt(65578); arr[j] = n; } try{ Sorting.heapSort(arr);} catch (EmptyHeapException ex){ System.out.println("Heap is empty, unable to sort array."); } catch (OutOfRangeException ex){ System.out.println("Error: Out of Range"); } Sorting.insertionSort(arr); Sorting.quicksort(arr); Sorting.quicksortImproved(arr); Arrays.sort(arr); } } }
but a stackOverflowError is thrown when I try to call for it from this one:
Java Syntax (Toggle Plain Text)
public class A5Q6 { public static void main(String[] args){ //Length of array is given by command argument int length = Integer.parseInt(args[0]); //100 arrays of variable lengths of elements of ascending values are created and then sorted for (int i=0; i < 100; i++){ int[] arr = new int[length]; int num = 0; for (int j = 0; j < length; j++){ Random rand = new Random(); int n = rand.nextInt(10); num += n; arr[j] = num; } try{ Sorting.heapSort(arr);} catch (EmptyHeapException ex){ System.out.println("Heap is empty, unable to sort array."); } catch (OutOfRangeException ex){ System.out.println("Error: Index is out of range."); } Sorting.insertionSort(arr); Sorting.quicksort(arr); Sorting.quicksortImproved(arr); Arrays.sort(arr); } } }
Any help will be greatly appreciated.
> 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.
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.
I don't accept change; I don't deserve to live.
•
•
Join Date: Dec 2008
Posts: 53
Reputation:
Solved Threads: 6
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).
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).
![]() |
Similar Threads
- Recursion: when do you use it? (C++)
- C++ Beginner - #include recursion problem (C++)
- Recursion (C++)
- number formatting using recursion (Java)
- Need help with recursion and arrays (C++)
- powers of two, recursion. (C)
- Create menu from properties file by recursion (Java)
- Recursion (C)
Other Threads in the Java Forum
- Previous Thread: Arraylist Problem Help Please
- Next Thread: Clock.java
| Thread Tools | Search this Thread |
android api applet application apps array arrays automation awt bidirectional binary birt bluetooth businessintelligence busy_handler(null) card class classes client code collision columns component constructor crashcourse database designadrawingapplicationusingjavajslider draw eclipse error errors eventlistener exception expand fractal game givemetehcodez graphics gui guidancer html ide image inetaddress integer intellij j2me java javadoc javafx javamicroeditionuseofmotionsensor javaprojects jme jni jpanel jtree julia linux list loop machine map method methods mobile mobiledevelopmentcreatejar myaggfun netbeans newbie oracle physics plazmic print problem program project radio recursion scanner server set sharepoint smart sms smsspam sort sortedmaps sql string subclass support swing textfield threads tree trolltech unlimited utility webservices windows






