C randomized pivot quicksort (improving the partition function)

后端 未结 2 582
小鲜肉
小鲜肉 2021-01-13 22:23

I\'m a computer science student (just started), I was working on writing from pseudocode a randomized pivot version of Quicksort. I\'ve written and tested it, and it all wor

2条回答
  •  独厮守ぢ
    2021-01-13 22:43

    This is the pseudo code of partition() from Introduction to Algorithms , which is called Lomuto's Partitioning Algorithm, and there's a good explanation below it in the book.

    PARTITION(A, p, r)
    1 x ← A[r]
    2 i ← p - 1
    3 for j ← p to r - 1
    4   do if A[j] ≤ x
    5       then i ←i + 1
    6           exchange A[i] ↔ A[j]
    7 exchange A[i + 1] ↔ A[r]
    8 return i +1
    

    You can implement a randomized partition implementation easily based on the pseudo code above. As the comment pointed out, move the srand() out of the partition.

    // srand(time(NULL));
    int partition(int* arr, int start, int end)
    {
        int pivot_index = start + rand() % (end - start + 1);
        int pivot = arr[pivot_index ];
    
        swap(&arr[pivot_index ], &arr[end]); // swap random pivot to end.
        pivot_index = end;
        int i = start -1;
    
        for(int j = start; j <= end - 1; j++)
        {
            if(arr[j] <= pivot)
            {
                i++;
                swap(&arr[i], &arr[j]);
            }
        }
        swap(&arr[i + 1], &arr[pivot_index]); // place the pivot to right place
    
        return i + 1;
    }
    

    And there is another partition method mentioned in the book, which is called Hoare's Partitioning Algorithm, the pseudo code is as below:

    Hoare-Partition(A, p, r)
    x = A[p]
    i = p - 1
    j = r + 1
    while true
        repeat
            j = j - 1
        until A[j] <= x
        repeat
            i = i + 1
        until A[i] >= x
        if i < j
            swap( A[i], A[j] )
        else
            return j
    

    After the partition, every element in A[p...j] ≤ every element in A[j+1...r]. So the quicksort would be:

    QUICKSORT (A, p, r)
    if p < r then
     q = Hoare-Partition(A, p, r)
     QUICKSORT(A, p, q)
     QUICKSORT(A, q+1, r)
    

提交回复
热议问题