排序——快速排序(quick_sort)
来源:互联网 发布:运动社交软件 推荐 编辑:程序博客网 时间:2024/05/22 00:40
快速排序(quick_sort)算法:
下面的代码都是按照升序来做的:
int quick_sort(int a[], int nL, int nR) //a是要排序的数组,nL是指向数组的左端,nR是指向数组的右端
{
int i, j;
int nKey;
if(nL < nR)
{
i = nL;
j = nR;
nKey = a[i];
while(i < j)
{
//Find the rigth num which is smaller than nKey and
//Put the num into nKey's position(a[i]).
while(i < j && a[j] > nKey)
j--;
if(i < j)
a[i++] = a[j];
//Find the left num which is larger than nKey and
//Put the num into the rigth empty position(a[j]).
while(i < j && a[i] < nKey)
i++;
if(i < j)
a[j] = a[i];
//Change the nKey's position,
//Just Put the nKey into the left empty position(a[i]).
a[i] = nKey;
}
quick_sort(a, nL, i-1);
quick_sort(a, i+1, nR);
}
}
在这个算法中要注意几个问题:
1)、在右边(左边一样的理)比 nKey 小的第一个元素的几段代码不可以改成如下形式:
while(i < j && a[j--] > nKey)
;
…………
…………
因为不管a[j--] > nKey 的真假,j--总是每次都要做一遍的。
假设找到了比 nKey 小的第一个元素 是 a[j] < nKey, 也就是a[j--] > nKey 为假了跳出循环,但找到的下标又做了 j--, 所以指向的不是要找到那个元素了,应该这样改下:
while(i < j && a[j--] > nKey)
;
j++;
…………
对于 while(i < j) 跟上面是一样的错误………………
{
if(a[j--] < nKey)
break;
}
2)、每次循环的最后 nKey 的位置 position 是要改变的。
每次循环,从左端找首个小于nKey填到nKey的位置, 再从右端找首个大于nKey的元素填到左端那个空出的位置,这样右端也空出个位置个,把nKey放进去。就这样循环下去…………
3)、最后递归调用的时候注意传入函数里的值
quick_sort(a, nL, i-1);
quick_sort(a, i+1, nR);
数组始终是那个数组, 但对数组的操作范围取决于 后面的左右边界。
下面的这个快速排序函数传入的参数是需要排序的数组和数组的长度(其实也就是数组的上边界和数组的下边界):
int quick_sort(int a[], int nLen) //a是需要排序的数组,nLen是数组的长度
{
int i, j;
int nKey;
if(nLen != 0)
{
i = 0;
j = nLen -1;
nKey = a[i];
while(i < j)
{
while(i < j && a[j] > nKey)
j--;
if(i < j)
a[i++] = a[j];
while(i < j && a[i] < nKey)
i++;
if(i < j)
a[j] = a[i];
a[i] = nKey;
}
quick_sort(a, i); //这里要特别注意传入的数组上界与数组长度
quick_sort(a+i+1, nLen-i -1); //…………
}
}
快速排序(quick_sort)在排序算法中很重要,而且对于大量数据的排序的效率也非常不错,所以要多加练习,掌握快速排序!
- 排序——快速排序(quick_sort)
- 快速排序quick_sort
- 快速排序Quick_Sort
- 快速排序(Quick_Sort)
- 快速排序的简单实现(Quick_Sort)
- 经典排序算法 - 快速排序Quick_sort
- 快速排序quick_sort(python的两种实现方式)
- quick_sort(快速排序)c语言实现
- 基于随机数作为基数的快速排序算法 quick_sort
- 排序—快速排序
- 排序 quick_sort 快排 算法 随机函数 rand() 快速排序的随机化版本
- 排序算法之快速排序<Quick_Sort>及其C语言代码实现
- 排序算法的时间复杂度比较(quick_sort;bubble_sort)
- 排序——快速排序(QuickSort)
- 排序——快速排序(QuickSort)
- 排序——快速排序(C++)
- (十六)高级排序—快速排序
- 排序——快速排序
- 调级申请
- Google的Linux集群解决方案
- GCC使用入门
- 加油
- 老司机总结出的21条开车经验
- 排序——快速排序(quick_sort)
- powerpoint中如何使用母版
- Converting VS2010 Solution to VS2008,将vs2010工程转换成vs2008
- 1. 开始
- winform学习积累
- logic:present 和 logic:empty的用法
- Random Shuffles
- 授权ARM架构,微软晚了三年
- HDU 1800(水题!!! @@)