introsort
是introspective sort的缩写,introspective的意思是内省的。他的名字就表达了他的思路,思路就是进行自我侦察反省,快排递归太深那就说明在这种数据序列下,选key出现了问题,性能在快速的退化,那么就不要再用快排分割递归了,该换为堆排序进行排序。思想很简单就是集中排序的结合,代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
void swap(int* a, int* b)//这是交换函数
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void adjustdown(int* ch, int parent, int end)
{
int child = parent * 2 + 1;
while (child <= end)
{
if (child + 1 <= end && ch[child] < ch[child + 1])//这里是对修改数据调整,调整为大堆
child++;
if (ch[child] > ch[parent])
{
int tmp = ch[child];
ch[child] = ch[parent];
ch[parent] = tmp;
parent = child;
child = parent * 2 + 1;
}
else
break;
}
}
void heapsort(int* ch,int end)
{
for (int i = (end - 1) / 2; i >= 0; i--)
adjustdown(ch, i, end);//这个过程是从下向上不断进行堆的向下调整,每次都能让数组的一部份变成大堆。
while (0 < end)//下面是排序。思想就是将大堆堆顶元素(该元素是堆中最大元素)与数组末尾元素交换
//然后再利用向下调整(此时堆里不应该包含刚刚交换过的堆顶元素)将剩下的堆调整为大堆,然后重复上面步骤。
{
int tmp = ch[end];
ch[end] = ch[0];
ch[0] = tmp;
end--;
adjustdown(ch, 0, end);
}
}
void insertsort(int* ch, int left, int right)//插入排序
{
for (int i = left + 1; i <= right; i++)
{
int tmp = ch[i];
int end = i - 1;
for (; end >= 0;)
{
if (tmp < ch[end])
{
ch[end + 1] = ch[end];
end--;
}
else
break;
}
ch[end + 1] = tmp;
}
}
void introsort(int* ch, int left, int right, int depth, int defaultdepth)
{
if (right <= left)
return;
if (right - left + 1 < 16)//对于小区间的优化
{
insertsort(ch, left, right);
return;
}
if (depth > defaultdepth)//对于太深递归的优化
{
heapsort((ch+left), right-left);
return;
}
int Left = left;
int Right = right;//记录位置
int key = ch[left];
int cur = left + 1;
while (cur <= right)
{
if (ch[cur] > key)
{
swap(&ch[cur], &ch[right]);
right--;
}
else if (ch[cur] < key)
{
swap(&ch[cur], &ch[left]);
left++;
cur++;
}
else
cur++;
}
introsort(ch, Left, left-1, depth + 1, defaultdepth);
introsort(ch, right+1, Right, depth + 1, defaultdepth);
}
int main()
{
int depth = 0;
int n = 0;
scanf("%d", &n);
int ch[100010] = { 0 };
for (int i = 0; i < n; i++)
scanf("%d", &ch[i]);
int defaultdepth = 2 * (int)log2(n);
introsort(ch, 0, n - 1, depth, defaultdepth);
int count = 0;
for (int i = 0; i < n; i++)
printf("%d ", ch[i]);
return 0;
}