您的位置:首页 > 其它

快速排序

2015-08-25 11:15 253 查看
快排注意知识点:

每一趟排序,都有一个元素会放到其最终的位置上

快排是个不稳定的算法

最好情况 最坏情况的区别

–运行时间 与 划分的区间是否对称 相关

最好, 时间复杂度 O(nlog2n)

最坏, 时间复杂度 O(n^2)

下面是参考严版教材的快排,可以敲上n遍了,debug运行 看每一步的结果

#include <stdio.h>

int a[50] = { 21, 25, 5, 17, 9, 23, 30, 0, 25, 21 };

int partion(int low, int high)
{
// 一趟排序
int pivot = a[low];
while (low < high)
{
while (low < high && a[high] >= pivot)
--high;
a[low] = a[high];
while (low < high && a[low] < pivot)
++low;
a[high] = a[low];
}
a[low] = pivot;  // 此时low 就是pivot 最终的位置
return low; // 返回最终确定的位置
}

void myqsort(int low, int high)
{
if (low >= high)
return ;
int left = low;
int right = high;

// 一趟排序
int pivot = a[low];
while (low < high)
{
// 从右往左 找到第一个小于pivot的 进行交换
while (low < high && a[high] >= pivot)
--high;
a[low] = a[high];
// 从左往右 找到第一个大于等于pivot的 进行交换
while (low < high && a[low] < pivot)
++low;
a[high] = a[low];
}
a[low] = pivot;  // 此时low 就是pivot 最终的位置

// 下面递归
myqsort(left, low - 1);
myqsort(low + 1, right);
}

void pf(int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main()
{
int n = 10;
myqsort(0, n-1);
pf(n);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: