Recently have time to learn about the quick sort and merge sort.
began to feel very difficult, has not chewed this bone, now found that understanding is not difficult.
The idea of a quick line is to specify a value and then lower his row to its left, greater than his row to the right.
1#include <iostream>2#include <Set>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 classSolution {8 Public:9 voidQsort (vector<int>& Nums,intLintu) {Ten if(l>=u) One { A return; - } - intm=l; the for(inti=l+1; i<=u;i++) - { - if(nums[i]<Nums[l]) - { +m++; - swap (nums[m],nums[i]); + } A } at swap (nums[m],nums[l]); -Qsort (nums,l,m-1); -Qsort (nums,m+1, u); - } - }; - in intMain () - { to solution so; +vector<int>input; -Input.push_back (6); theInput.push_back (5); *Input.push_back (3); $Input.push_back (1);Panax NotoginsengInput.push_back (8); -Input.push_back (7); theInput.push_back (2); +Input.push_back (4); ASo.qsort (Input,0, Input.size ()-1); the}
Merge the new space, dissolve the problem into small parts, and combine the edge sort.
1#include <iostream>2#include <Set>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 classSolution {8 Public:9 voidMerge (vector<int>& Nums,intPintQintR)Ten { One intN1 = q-p+1; A intN2 = RQ; -vector<int> Left (N1,0); -vector<int> Right (N2,0); the for(intI=0; i<n1;i++) - { -left[i]=nums[p+i]; - } + for(intI=0; i<n2;i++) - { +right[i]=nums[q+i+1]; A } at intI=0, j=0; - intk=p; - while(I<n1 && j<n2) - { - if(left[i]<=Right[j]) - { innums[k++]=left[i++]; - } to Else + { -nums[k++]=right[j++]; the } * } $ for(; i<n1;i++)Panax Notoginseng { -nums[k++]=Left[i]; the } + for(; j<n2;j++) A { thenums[k++]=Right[j]; + } - } $ voidMergeSort (vector<int>& Nums,intPintR) $ { - if(p<R) - { the intq= (P+R)/2; - mergesort (nums,p,q);WuyiMergeSort (nums,q+1, R); the Merge (nums,p,q,r); - } Wu } - }; About $ intMain () - { - solution so; -vector<int>input; AInput.push_back (6); +Input.push_back (5); theInput.push_back (3); -Input.push_back (1); $Input.push_back (8); theInput.push_back (7); theInput.push_back (2); theInput.push_back (4); theSo. MergeSort (Input,0, Input.size ()-1); -}
[Problem] Quick sort and merge sort