简体   繁体   English

QuickSort:此实现有什么问题

[英]QuickSort: what is wrong with this implementation

Can you explain what is wrong with this quicksort algorithm implementation in java? 您能解释一下Java中这种quicksort算法实现的问题吗?

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. 一个明显的错误是大小为1的数组未正确处理。 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. 该算法的主要问题-您正在为函数的每次调用创建新的ArrayList。 In this way you nullify the best thing about QuickSort - sorting in place without any additional memory. 这样,您就可以使有关QuickSort的最好的东西无效-无需任何额外的内存就位排序。 Try to work only with the first given array . 尝试仅使用第一个给定的数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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