Quick sort pits quite a bit, today is free to record your own implementation, plus detailed comments and examples
#include <iostream>using namespacestd;intPartion (intNum[],intLeftintRight ) { intI,j,index,exchage; Index=Num[left]; I= left;//since while (I < J) has been decided, if i = left + 1, and the array has only two elements and J points to a larger element, such as 3 8 then the loop will not execute, and finally the 8 and 3 are exchangedj =Right ; while(I<J)//3 7 2 4 The following sawp is executed to 3 2 7 4 When I point to 7 J pointing to 2, there is no need to recycle J is the final position { while(Num[i] <= index && i < right)//I < Right is in order to deal with 100 2 3 4 This situation, I will always scan out of bounds, why not i<= right, because already j in right, will deal with that elementi++; while(Num[j] >= index && J > left)//J > left is to handle 13 2 1 4 In this case, J will always scan to 13 of the right side of the border, note j is > Ieft, not >i otherwise 3 8 This situation is wrongj--; if(I <j) Swap (Num[i++],num[j--]);//Loop End Three cases, the first of which is 3 7 2 4 The second is 3 3 1,i = = right = J End, when I j must be together, there is no need to exchange//The Third Kind is 3 7 9 This time J exits the loop because the cross judgment fails, why is it out of bounds, because it touches the first element, this time cannot exchange 3 and 7, because I stopped at a place larger than the first element} swap (Num[left],num[j]);//from small to large sort note is Exchange J and index position! returnJ;}voidQuick_sort (intNum[],intLointhi) { if(lo<hi) { intx = partion (Num,lo,hi);//for 3 8, x = 0Quick_sort (num,lo,x-1);//0 to 1 so to Judge Lo <= hi if is equal toQuick_sort (num,x+1, HI);//1 to 1, because there is only one element 8, there is no need to sort it so the above commented Lo <= hi is changed to lo < hi }}intMain () {inta[5] = {3,4,2,1,0 }; Quick_sort (A,0,4); for(i=0;i<5; i++) cout<< A[i] <<Endl; return 0;}
C + + Implementation Quick Sort detailed analysis