标签:排序 addclass ddc line sort nbsp tracking script from
和之前学习到的归并排序一样。高速排序也使用了分治的思想。
如果现有一个数组a[start,end],对这个数组进行高速排序分了以下三个步骤:
int partition(int* a, int start, int end)
{
int x = a[end];
int i = start;
//调整整个数组中元素的位置并找出中间值的索引
for (int j = start; j < end; j++)
{
if (a[j] <= x)
{
int t = a[i];
a[i] = a[j];
a[j] = t;
i++;
}
}
//将中间值放在找出的中间值索引处
int t = a[i];
a[i] = a[end];
a[end] = t;
return i;
}
void quick_sort(int* a, int from, int to)
{
if (from < to)
{
int p = partition(a, from, to);
quick_sort(a, from, p - 1);
quick_sort(a, p + 1, to);
}
}
void main()
{
int count, *p;
printf("请输入须要排序的数的个数 :");
scanf_s("%d", &count);
p = (int*)malloc(count * 2);
printf("\n请输入须要排序的%d个数字:",count);
for (int i = 0; i < count; i++)
{
scanf_s("%d", p+i);
}
printf("\n高速排序后的数组:");
quick_sort(p, 0, count - 1);
for (int i = 0; i < count; i++)
{
printf("%d ", p[i]);
}
printf("\n");
system("pause");
}
标签:排序 addclass ddc line sort nbsp tracking script from
原文地址:http://www.cnblogs.com/brucemengbm/p/6973322.html