void insertSort(int a[], int len)
{
for (int i = 1; i < len; ++i)
{
int j;
int temp = a[i];
for (j = i - 1; j >= 0; --j)
{
if (a[j] <= temp)
break;
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int median3(int a[], int left, int right)
{
int center = (left + right) >> 1;
if (a[left] > a[center])
swap(&a[left], &a[center]);
if (a[left] > a[right])
swap(&a[left], &a[right]);
if (a[center] > a[right])
swap(&a[center], &a[right]);
swap(&a[center], &a[right - 1]); // hide pivot
return a[right - 1];
}
const int cutoff = 3;
void quickSort(int a[], int left, int right)
{
int i, j;
int pivot;
if (left + cutoff <= right)
{
pivot = median3(a, left, right);
i = left, j = right - 1;
while (true)
{
while (a[++i] < pivot) {}
while (a[--j] > pivot) {}
if (i < j)
swap(&a[i], &a[j]);
else
break;
}
swap(&a[i], &a[right - 1]); // restore pivot
quickSort(a, left, i - 1);
quickSort(a, i + 1, right);
}
else
insertSort(a + left, right - left + 1);
}