Quick sort partition algorithm

拜拜、爱过 提交于 2019-12-31 07:18:07

问题


void partition(int *a, int size) {
   int pivot = a[0];
   int left = 0, right = 0;
   for(left = 1, right = size-1; left <= right; left++, right--) {
       if(a[left] >= pivot && a[right] <= pivot){
           swap(left, right, a);
       }
   }
   swap(0, right, a);
}

I wrote this method to partition an array as a preliminary step in order to apply quick sort, I tested it on this sample data:

8 2 5 13 4 19 12 6 3 11 10 7 9

the correct output should be:

6 2 5 7 4 3 8 12 19 11 10 13 9

but the actual output is:

6 2 5 13 4 3 8 12 19 11 10 7 9

The algorithm has to swap 13 with 7 but it fails due to the && condition in the above loop. I want to increment left only if a[left] >= pivot and decrement right only if a[right]<= pivot.


回答1:


You more or less answered your own question. You probably want to do something like this:

void partition(int *a, int size) {
    int pivot = a[0];
    int left, right;
    for(left = 1, right = size-1; left < right; )
    {
        if(a[left] > pivot && a[right] <= pivot)
        {
            swap(left, right, a);
        }
        if(a[left] <= pivot) left++;
        if(a[right] > pivot) right--;
    }
}



回答2:


here is another option, little bit more similar to the original one

int partition(int arr[], int left, int right)
{
    int pivot = arr[left];
    while (left != right)
    {
        if (arr[left] > arr[right])
        {
            swap(arr[left], arr[right]);
        }
        if (pivot == arr[left])
            right--;
        else // Pivot == arr[right]
            left++;
    }
    return left;
}


来源:https://stackoverflow.com/questions/13782209/quick-sort-partition-algorithm

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