要面试啊明天,顺便复习了一下快速排序算法。
总体思路如下:
1:随时获得需要排序的某个元素 (数组arr[1000], 随机索引为ranIndex = 48)
2:循环次数为递归调用的参数,第一次递归循环次数为(sizeof(arr))
3:从数组末尾向随机索引开始遍历,如碰到比索引值小的数,则进行交换,跳至第三步
4:从数组首部向随机索引位置开始遍历,如碰到比索引值大的数,则进行交换,跳至下次循环
5:循环完毕之后随机索引值就能找到它在数组中的正确位置(比如arr[1000]中随机分部着0-1000的数字,随机索引ranIndex = 48,arr[48] = 70, 则70的正确位置应该是arr[70])
6:将数组从最终结果位置拆成两个数组,分别递归调用快速排序函数
7:直到细分的数组中只剩下一个元素,排序结束
void qkSort(vector<int>& pList, int low, int high) { if(low >= high) return; int startIndex = low; int refValue = pList[startIndex]; int ilow = low, ihigh = high; while(ilow < ihigh) { for(/*int i = high*/; ihigh > startIndex; ihigh--) { count ++; int nowValue = pList[ihigh]; if(nowValue <= refValue) { swapNum(pList, ihigh, startIndex); startIndex = ihigh; break; } } for(/*int j = low*/; ilow < startIndex; ilow++) { count ++; int nowValue = pList[ilow]; if(nowValue > refValue) { swapNum(pList, ilow, startIndex); startIndex = ilow; break; } } ilow++; } if(low < startIndex - 1) qkSort(pList, low, startIndex - 1); if(startIndex + 1 < high) qkSort(pList, startIndex + 1, high); } void swapNum(vector<int>& pList, int i, int j) { int tmp = pList[i]; pList[i] = pList[j]; pList[j] = tmp; }
原文:http://www.cnblogs.com/jiaqi/p/3608928.html