Skip to content

Instantly share code, notes, and snippets.

@kingsamchen
Last active December 16, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingsamchen/5371675 to your computer and use it in GitHub Desktop.
Save kingsamchen/5371675 to your computer and use it in GitHub Desktop.
two usual versions of implementations
int Partition(int a[], int left, int right)
{
int piv = a[left];
int l = left, r = right + 1;
do
{
do
{
++l;
} while (a[l] < piv && l < r);
do
{
--r;
} while (a[r] > piv);
if (l < r)
{
std::swap(a[l], a[r]);
}
else
break;
}while (l < r);
std::swap(a[left], a[r]);
return r;
}
int Partition(int a[], int left, int right)
{
// pick the pivot from median of the three
int mid = (left + right) >> 1;
if (a[left] > a[mid])
{
std::swap(a[left], a[mid]);
}
if (a[mid]> a[right])
{
std::swap(a[mid], a[right]);
}
if (a[left] > a[mid])
{
std::swap(a[left], a[mid]);
}
/* {a[left] <= a[mid] <= a[right]} */
std::swap(a[mid], a[right-1]);
int pivot = a[right-1];
int l = left;
int r = right - 1;
do
{
while (a[++l] < pivot)
{
}
while (a[--r] > pivot)
{
}
if (l < r)
{
std::swap(a[l], a[r]);
}
} while (l < r);
std::swap(a[l], a[right-1]);
return l;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment