简体   繁体   中英

QuickSort: what is wrong with this implementation

Can you explain what is wrong with this quicksort algorithm implementation in java?

static ArrayList<Integer> quickSort(ArrayList<Integer> array){

    if (array.size() <=1){
        ArrayList<Integer> a = new ArrayList<Integer>();

        return a;
    }

    int pivotIndex = array.size() / 2;

    int pivot = array.get(pivotIndex);
    ArrayList<Integer> left= new ArrayList<Integer>();
    ArrayList<Integer> right = new ArrayList<Integer>();

    for (int i = 0; i < array.size(); i++) {
        if (i!=pivotIndex){
        if (array.get(i) > pivot)
            right.add(array.get(i));
        else
            left.add(array.get(i));
        }

    }
    ArrayList<Integer> l = new ArrayList<Integer>();
    l.addAll(quickSort(left));
     l.add(pivot);
     l.addAll(quickSort(right)); 

    return l;

}

One glaring error is that arrays of size one are not handled correctly. It's important to get this right since this is one of the base cases for the recursion.

instead of

if (array.size() <=1) {
    ArrayList<Integer> a = new ArrayList<Integer>();

    return a;
}

use

   if (array.size() <=1){
   return array
}

The main issue with this algorithm - you're creating new ArrayLists for each invocation of the function. In this way you nullify the best thing about QuickSort - sorting in place without any additional memory. Try to work only with the first given array .

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