简体   繁体   中英

Is this a valid quicksort implementation?

Is this a valid implementation of 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...

//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)) .

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 .

For instance: 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 . 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.

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