What is the purpose of these lines of swap code in quicksort application?

空扰寡人 提交于 2019-12-04 06:58:29

问题


I am trying to understand an implementation or an application of quicksort to find the kth smallest element Here is the code that I am trying to understand

public int quicksort(int a[], int start, int end, int k) {
    if(start < end) {
        int pivot = partition(a, start, end);
        if(pivot == k -1) {
            return pivot;
        } else if(pivot > k - 1){
            return quicksort(a, start, pivot, k);
        } else {
            return quicksort(a, pivot + 1, end, k);
        }
    } else if(start == end) {
        return k==1?start:-1;
    } else {
        return -1;
    }
}
public int partition(int a[], int start, int end) {
    int pivot = start;
    int i = pivot + 1;
    int j = end;
    while(a[i] < a[pivot] && i < end) {
        i ++;
    } 
    while(a[j] > a[pivot] && j >= 0) {
        j --;
    } 
    if(i < j) {
        swap(a, start, end);
    }
    swap(a,j, pivot);
    return pivot;
}
private void swap(int a[], int swap1, int swap2) {
    int temp = a[swap1];
    a[swap1] = a[swap2];
    a[swap2] = temp;
}

I understand for trying to find the kth smallest element, you want to use quicksort because elements to the left of pivot will be less than the pivot and elements to the right of the pivot will be greater than. So that way if you're trying to find the 4th smallest element, and the pivot is at index 3, you can just return it because you know it is the 4th smallest since there are 3 elements smaller than it.

I am having trouble understanding the two swaps in the partition method.

At the conclusion of the first while loop, index i will be at a position at which all elements less than the pivot will be to the left of i. Index j will be at a position at which all elements greater than the pivot will be to the right of j.

What is the purpose of this swap code inside partition? Can anyone give an example of why this of code is necessary? How will these ever meet?

if(i < j) {
        swap(a, i, j);
}

And also for this swap line(also inside partition), why did the author swap pivot and j, and not pivot and i? Is it arbitrary?

        swap(a,j, pivot);

回答1:


You can use the partition algorithm present at : Quick sort partition algorithm

The algorithm you are using returns incorrect pivot



来源:https://stackoverflow.com/questions/28104147/what-is-the-purpose-of-these-lines-of-swap-code-in-quicksort-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!