Quick sorting and quick sorting algorithms
Quick sorting is an improvement of Bubble sorting. The basic idea is to split the records to be sorted into two separate parts by one sort. the keywords of some records are smaller than those of other records, then, the two records can be sorted separately to achieve the whole sequence order. Suppose the sequence to be sorted is {a [L], a [L + 1], a [L + 2],…, A [R]}, first select any record (usually an intermediate record can be used as the pivot or pivot point), and then rearrange the remaining records, place all records whose keywords are less than the keyword in the left subsequence, and all records whose keywords are greater than the keyword in the right subsequence. Therefore, the "pivot" record's position mid can be used as the demarcation line to divide the sequence into two subsequences and. This process is called a Quick Sort (or a division ). The specific method of a quick sort is: with two pointers I and j, their initial values are L and R, respectively, and the pivot record is set to mid, first, search for the record with the first keyword less than the mid from the position indicated by j, and then search for the record with the first keyword greater than the mid from the position indicated by I, exchange them and repeat these two steps until I> j. The complexity of quick sorting is O (nlog2n), which is fast, but it is an unstable sorting method. In terms of average time, fast sorting is currently considered as the best internal sorting method. From the above discussions, we can see that, in terms of time, the average performance of quick sorting is better than the various sorting methods discussed earlier. However, quick sorting requires a stack space to implement recursion. If each sort splits the record sequence evenly into two subsequences with the same length, the maximum depth of the stack is log (n + 1 ).
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 int a[10001]; 5 6 int n; 7 void qsort(int l,int r) 8 { 9 int i=l;10 int j=r;11 int mid=a[(l+r)/2];12 do13 {14 while(a[i]<mid&&i<=j)15 {16 i++;17 }18 while(a[j]>mid&&i<=j)19 j--;20 if(i<=j)21 {22 swap(a[i],a[j]);23 i++;24 j--;25 }26 }while(i<=j);27 if(l<j)28 qsort(l,j);29 if(i<r)30 qsort(i,r);31 }32 int main()33 {34 35 cin>>n;36 for(int i=0;i<n;i++)37 {38 cin>>a[i];39 }40 qsort(0,n-1);41 for(int i=0;i<n;i++)42 cout<<a[i]<<" ";43 return 0;44 }