For the following quicksort algorithm:
import java.util.Scanner;
import java.util.ArrayList;
public class quick_sort_demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> my_arr = new ArrayList<Integer>();
while (true) {
System.out.println("Enter input value. '-1' to exit the adding process. ");
int val = sc.nextInt();
sc.nextLine();
if (val == -1) {
break;
} else {
my_arr.add(val);
}
}
quick_sort(my_arr);
}
public static ArrayList<Integer> quick_sort(ArrayList<Integer> arr) {
if (arr.size() <= 1) {
return arr;
}
int pivot_index = (int) (Math.random() * arr.size());
int pivot = arr.get(pivot_index);
ArrayList<Integer> left_arr = new ArrayList<Integer>();
ArrayList<Integer> right_arr = new ArrayList<Integer>();
for (int i = 0; i < arr.size(); i++) {
int element = arr.get(i);
if (element > pivot) {
right_arr.add(element);
} else {
left_arr.add(element);
}
}
left_arr = quick_sort(left_arr);
right_arr = quick_sort(right_arr);
ArrayList<Integer> result = new ArrayList<Integer>();
result.addAll(left_arr);
result.add(pivot);
result.addAll(right_arr);
return result;
}
}
I am getting this error repeatedly:
Exception in thread "main" java.lang.StackOverflowError
at java.base/java.util.Random.next(Random.java:209)
at java.base/java.util.Random.nextDouble(Random.java:463)
at java.base/java.lang.Math.random(Math.java:865)
at quick_sort_demo.quick_sort(quick_sort_demo.java:23)
at quick_sort_demo.quick_sort(quick_sort_demo.java:35)
My exact inputs for the program were as follows: {6,15,32,643,6543,534232,232,-1}
I tried asking CHATGPT but I couldn't get a helpful answer for the specific error I encountered. I don't understand why I'm getting a stackoverflow error as the recursive method should be calling itself without issue until the 'arr.size()' returns something <= 1. Can someone explain what I'm doing wrong? Is my algorithm wrong and why am I getting a recursion error?
well almost fine, there is a bug in your code
left_arr = quick_sort(left_arr);
right_arr = quick_sort(right_arr);
ArrayList<Integer> result = new ArrayList<Integer>();
result.addAll(left_arr);
result.add(pivot); //BUG HERE
result.addAll(right_arr);
when you split left/right you already add your pivot
into the left_arr
- so no need to add it twice, since
if (element > pivot) {
right_arr.add(element);
} else {
left_arr.add(element); //pivot itself is NOT bigger than pivot and will be added here
}
alternatively you can remove
the pivot from the list: int pivot = arr.remove(pivot_index);
well - your code is working fine, on my machine so i guess you have to setup your computer properly - see this answer for further details (sorry for that link-only answer)