Quick sort partition algorithm

前端 未结 2 1521
轻奢々
轻奢々 2021-01-27 07:11
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[lef         


        
相关标签:
2条回答
  • 2021-01-27 07:33

    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--;
        }
    }
    
    0 讨论(0)
  • 2021-01-27 07:54

    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;
    }
    
    0 讨论(0)
提交回复
热议问题