简体   繁体   English

这是有效的quicksort实现吗?

[英]Is this a valid quicksort implementation?

Is this a valid implementation of quicksort? 这是quicksort的有效实现吗? It is different from how I have seen it implemented elsewhere, but I find it easier personally to implement it this way. 它与我在其他地方看到的实现方式不同,但是我发现以这种方式实现它比较容易。 As far as I can tell, it is still in-place and O(n log n) [edit: O(n log n) expected run time, O(n^2) worst-case], but want to make sure before I do it in a job interview and look like an idiot... 据我所知,它仍然在原位,并且O(n log n)[编辑:O(n log n)预期运行时间,O(n ^ 2)最坏的情况],但要确保在我是在求职面试中做的,看起来像个白痴。

//Quicksort of arr between low and high
public static void myqs(int[] arr, int low, int high){
    if(arr == null){
        return;
    }

    if(low >= high){
        return;
    }

    //get pivot value, put it at the end of the chunk
    int pivotIndex = low + ((high - low) / 2);
    int pivot = arr[pivotIndex];
    swap(arr,pivotIndex,high);

    //move any lower number to the low end of chunk
    int lowIndex = low;
    for(int i = low; i < high; i++){
        if(arr[i] < pivot){
            swap(arr,lowIndex,i);
            lowIndex++;
        }
    }
    //move pivot value between low/high chunks
    swap(arr, lowIndex, high);

    //recurse on lower/upper halves
    myqs(arr, low, lowIndex - 1);
    myqs(arr, lowIndex + 1, high);
}

//swap values at indices i and j in arr
public static void swap(int[] arr, int i, int j){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

It looks good (but you should try it to be sure), but it is not in O(n log(n)) . 看起来不错(但您应该尝试确定),但是它不在O(n log(n))

Indeed, it is possible to send a particular array that will trigger n recursive calls, by always having the greatest value as the middle, which gives a total complexity of N^2 . 确实,可以通过始终将最大值作为中间值来发送将触发n递归调用的特定数组,这将使总复杂度为N^2

For instance: 1, 2, 3, 7, 4, 5, 6 . 例如: 1, 2, 3, 7, 4, 5, 6 7 will be the pivot, so the array will be divided into an empty array and 1, 2, 3, 4, 5, 6 . 7将成为枢轴,因此该数组将分为一个空数组和1, 2, 3, 4, 5, 6 In that case, only the first split is “bad”, but you can easily imagine how one can make all splits bad. 在这种情况下,只有第一个拆分是“坏的”,但是您可以轻松地想象一个如何使所有拆分成为坏的。

To get an O(N log(N)) average complexity, the most popular solution is to chose the pivot randomly. 为了获得O(N log(N)) 平均复杂度,最流行的解决方案是随机选择枢轴。

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

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