Sort algorithm-Quick sort

Source: Internet
Author: User

First quick sort, the data structure after the study, put some sort just understand thought, has not realized, today took time to realize a bit
The idea of a quick sort is to randomly select a number from a period of time, place the element smaller than it in front of the element, place it in the back of it, and then apply the idea of split, respectively, to the two ends separated by the current element, and then recursively, because each time a number is randomly selected, So it's not stable, but it's still a good combination of speed.
Tested on HDOJ, and the efficiency of calling STL library functions is basically the same. It's still very satisfying.
Its implementation code:

#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <ctime>Using namespace Std;constintN =100000;intA[n];intRandom (intNUM) {return(int) num * (double)Rand()/rand_max;}intRandominrange (intStartintEnd) {Srand( Time(NULL));returnStart + Random (end-start-1);}intPartition (intLenintStartintEnd) {int Index= Randominrange (start,end);//int Index= (start+end)/2; Swap (a[end],a[Index]);intsmall = Start-1; for(Index= start;Index< end; ++Index)    {if(a[Index] < A[end])///Swap the element smaller than the current to the front of the array {++small;        if (small! = index) swap (A[index],a[small]);    }} ++small;  Swap (a[small],a[end]); ///The element is exchanged to the middlereturnSmall;} void QuickSort (intLenintStartintEnd) {if(start = = end)return;int Index= Partition (len,start,end);if(Index> Start) QuickSort (Len,start,Index-1);if(Index< end) QuickSort (Len,Index+1, end);}intMain () {//freopen("Input.txt","R", stdin);intN while(~SCANF ("%d", &n)) { for(intI=0; i<n; i++) scanf ("%d", &a[i]); QuickSort (N,0, N-1); for(intI=0; i<n; i++)printf("%d ", A[i]); Puts""); }return 0;}

Sort algorithm-Quick sort

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.