算法——快速排序
来源:互联网 发布:w3c php手册下载 编辑:程序博客网 时间:2024/06/14 04:21
快速排序算法的实现
利用快速排序算法对int型数组进行排序
#include <stdio.h>#include <stdlib.h>#include <windows.h>void QSort( int Array[], int start, int end ){ if( start >= end ) return; // 如果标准值放到该位置,则所有左边的数值都比标准值小 int smallPos = start; // 如果标准值放到该位置,则所有右边的数值比标准值大 int bigPos = end; // 标准值调整位置,非必要,但是添加这个可以让整体代码更加清晰 int insertPos = 0; int standardValue = Array[start]; while( smallPos < bigPos ) { // 从右边开始往左边找,smallPos < bigPos条件必须有,否则极端情况下 bigPos 可能等于-1 while( smallPos < bigPos && Array[bigPos] >= standardValue ) bigPos--; if( smallPos < bigPos ) { Array[smallPos] = Array[bigPos]; smallPos++; } // 从左边开始往右边找,,smallPos < bigPos条件必须有,否则极端情况下 smallPos 可能超过最大下标 while( smallPos < bigPos && Array[smallPos] < standardValue ) smallPos++; if( smallPos < bigPos ) { Array[bigPos] = Array[smallPos]; bigPos--; } } // 此时 smallPos 和 bigPos 相等,那么表示标准值放在该位置能同时保证左边的数值都比标准值小,右边的都大于等于标准值,完成一次排序 insertPos = smallPos; Array[insertPos] = standardValue; // 终究我们把所有大于标准值的扔到了右边,小于标准值的扔到了左边 // 那么剩下的是重新对剩下的两边重新进行排序就行了 QSort( Array, start, insertPos - 1 ); QSort( Array, insertPos + 1, end );}// 获得随机的数void GenRandomData( int Array[], int Count ){ for( int i = 0; i < Count; i++ ) { Array[i] = rand() % 10; }}void IsSort( int Array[], int Count ){ for( int i = 1; i < Count; i++ ) { if( Array[i] < Array[i-1] ) { printf( "Array is not sort !\n" ); return; } } printf( "Array is sort !\n" );}int main( int argc, char* argv[] ){ srand( GetTickCount() ); int Array[10] = {0}; GenRandomData( Array, 10 ); IsSort( Array, 10 ); QSort( Array, 0, 9 ); IsSort( Array, 10 ); return 0;}
运行结果:
其实快去排序就是从两头往中间查找一个位置,使得把标准值插入该位置以后左边的数比标准值小,右边比标准值大即可。
第一次排序保证AB区域比AC区域的数都小
第二次排序保证AV < VB < BW < WC区域
…
(但是各区域内部顺序不需要保证,靠递归继续排序)
…
最终各区域只有一个值的时候,整个数组就排序完毕了
【返回】
算法——分类目录
0 0
- 排序算法—快速排序
- 排序算法—快速排序
- 【算法】——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法——快速排序
- 算法导论—快速排序
- 啊哈!算法—快速排序
- 排序算法———快速排序
- 排序算法(一)——快速排序
- 排序算法——快速排序
- 排序算法——快速排序
- 经典排序算法——快速排序
- 安卓软件盘的开启与关闭
- 微信小程序开发详解(六)---微信小程序配置
- Unity使用UGUI进行VR游戏的界面开发
- 机器学习在金融大数据风险建模中的应用
- pod install速度慢的终极解决方案
- 算法——快速排序
- 04_1Python绘图_matplotlib
- asp.net(C#)通过WMI无法获取磁盘卷序列号(硬件信息)的问题解决办
- JS(三)generator
- Mac OS X下从服务进程中启动另一个应用程序(Cocoa Application)
- MySQL大表优化方案
- iOS的Cocoa 及NS框架
- 数据库协作运维大势所趋
- php数据库操作-创建库和表以及插入数据