Wednesday, June 1, 2011

Quicksoft Notes - 2011/06/01

Using the partition, the first pivot is using the a[right] or a[left+(right-left)/2]. For the latter, remember to swap the a[left+(right-left)/2] to the a[right] firstly.

Then
void quicksort(int* array, int left, int right)
{
if (right > left) // subarray of 0 or 1 elements already sorted
{
    //select a pivotIndex in the range left ≤ pivotIndex ≤ right
    // see Choice of pivot for possible choices
    int pivotIndex = left+(right-left)/2;
    int pivotNewIndex = inplace_partition(array, left, right,pivotIndex); // element at pivotNewIndex is now at its final position
    quicksort(array, left, pivotNewIndex - 1); // recursively sort elements on the left of pivotNewIndex
    quicksort(array, pivotNewIndex + 1, right); // recursively sort elements on the right of pivotNewIndex
}
}

One interesting thing for swap:
Can you see any problem for such code looking wise?
void swap(int& a, int& b)
{

a = a + b;
b = a - b;
a = a - b;
}

Reference: Introduction to Algorithms, Chapter 7.1.