简体   繁体   中英

How can I fix my java quick sort?

The problem is, it's a neverending recursion. I don't know, how can I finish the recursion. The funny is, it works, if I print the arraylist (mergedArray), it will be sorted after some iteration, but the function never stops. The error message is:

"at javaapplication9.QuickSort.simple_quick_sort(QuickSort.java:40)"

The code below:

public ArrayList<Integer> simple_quick_sort(ArrayList<Integer> arr) {
    ArrayList<Integer> mergedArray = new ArrayList<Integer>();
    ArrayList<Integer> left = new ArrayList<Integer>();
    ArrayList<Integer> right = new ArrayList<Integer>();
    if (arr.size() <= 1) {
        return arr;
    }
    else {
        int pivot = arr.get(0);
        for (int i = 0; i < arr.size(); i++) {
            if (arr.get(i) < pivot) {
                left.add(arr.get(i));
            }
            else {
                right.add(arr.get(i));
            }
        }

    } 
    mergedArray.addAll(left);
    mergedArray.addAll(right);
    simple_quick_sort(mergedArray);
    return mergedArray;
}
public ArrayList<Integer> simple_quick_sort(ArrayList<Integer> arr) {

  if (arr.size() <= 1) {
    return arr;
  }
  else {
    ArrayList<Integer> mergedArray = new ArrayList<Integer>();
    ArrayList<Integer> left = new ArrayList<Integer>();
    ArrayList<Integer> right = new ArrayList<Integer>();
    int pivot = arr.get(0);
    for (int i = 0; i < arr.size(); i++) {
        if (arr.get(i) < pivot) {
            left.add(arr.get(i));
            left = simple_quick_sort(left);
        }
        else {
            right.add(arr.get(i));
            right = simple_quick_sort(right);
        }
    }

  } 
  mergedArray.addAll(left);
  mergedArray.addAll(right);
}

Of course, copying is contrary to the basic idea of quicksort which is good because it can work on the array to be sorted, not requiring these copy operations and storage allocations.

I am sorry but your entire implementation of quicksort is kind of incorrect. Also, using a loop inside of a recursive function negates the benefits of using recursion. If you want to implement that loop, I would suggest you nest it inside another loop to make the code simpler (won't be as efficient as recursion).

If you want to continue with this program, try making the following change: When you write

simple_quick_sort(mergedArray);
return mergedArray;

you are not using the returned value from the function. You are just calling the function and doing nothing with the returned value. There might be more things that need fixing before this code works. If you want to learn more about quick sort and recursion, I found this page http://www.geeksforgeeks.org/quick-sort/

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM