快速排序(Hoare 分割)
作者:互联网
1. 使用 median of three得到分割点
2.当待排序数组的长度小于阈值(10)的时候,切换到插入排序
代码:
void insertion_sort(int *a, int start, int end)
{
int i, j;
for(i = start + 1; i <= end; ++i)
{
int k = a[i];
for( j = i - 1; (j >= start) && (a[j] > k); --j)
{
a[j+1] = a[j];
}
a[j+1] = k;
}
}
int swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int median(int *a, int start, int end)
{
int mid = (start + end) / 2;
if( a[mid] < a[start] )
{
swap(&a[mid], &a[start]);
}
if(a[end] < a[start])
{
swap(&a[start], &a[end]);
}
if(a[end] < a[mid])
{
swap(&a[end], &a[mid]);
}
swap(&a[mid], &a[end -1]);
return a[end -1];
}
void _quick_sort(int *a, int start, int end)
{
if( start + 10 <= end)
{
int i, j;
for(;;)
{
i = start, j = end - 1;
int med = median(a, start, end);
while(a[++i] < med) {};
while(a[--j] > med) {};
if( i < j)
{
swap( &a[i], &a[j]);
}
else
{
break;
}
}
swap(&a[i], &a[end - 1]);
printf("i = %d\n", i);
_quick_sort(a, start, i - 1);
_quick_sort(a, i + 1, end);
}
else
{
insertion_sort(a, start, end);
}
}
void quick_sort(int *a, int size)
{
_quick_sort(a, 0, size - 1);
}
标签:sort,分割,end,int,mid,start,swap,Hoare,排序 来源: https://blog.csdn.net/CaspianSea/article/details/89325244