1. Merge sort
1 voidMergeSort (vector<int>& Nums,intStartintend) {2 if(start<end) {3 intQ = (start+end)/2;4 mergesort (nums,start,q);5MergeSort (nums,q+1, end);6 merge (nums,start,q,end);7 }8 }9 voidMerge (vector<int>& Nums,intStartintQintend) {Tenvector<int> L1 (q-start+1,0); Onevector<int> L2 (end-q,0); AL1.assign (Nums.begin () +start,nums.begin () +q+1); -L2.assign (Nums.begin () +q+1, Nums.begin () +end+1); - intI=0, j=0; the for(intK = start;k<=end;k++){ - if(L1[i] <=L2[j]) { -NUMS[K] =L1[i]; -i++; +}Else{ -NUMS[K] =L2[j]; +J + +; A } at if(I>l1.size ()-1){ - for(ints = k +1; s<=end;s++){ -Nums[s] =L2[j]; -J + +; - } - Break; in } - if(J>l2.size ()-1){ to for(ints = k +1; s<=end;s++){ +Nums[s] =L1[i]; -i++; the } * Break; $ }Panax Notoginseng } -}
Using the divide-and-conquer method, the elements are first split into the smallest form, and then 22 are merged. Each merge is a merge of two already sequenced sub-arrays.
However, when an array is merged, it needs to be copied into the array of the new request, and the copy process takes time and additional memory overhead.
2. Quick Sort
voidQuickSort (vector<int>& Nums,intStartintend) { intpivot; if(start<end) {Pivot=randpartition (nums,start,end); QuickSort (Nums,start,pivot-1); QuickSort (Nums,pivot+1, end); } } intRandpartition (vector<int>& Nums,intStart,intend) { intRandi =start; Std::swap (Nums[randi],nums[start]); intPivot =Nums[start]; inti =start; for(intj = start+1; j<=end;j++){ if(nums[j]<pivot) {i++; Swap (nums[i],nums[j]); }} swap (Nums[start],nums[i]); returni; }
Random fast sorting does not require additional memory space, randomly select pivot array to divide, so that the left element is less than pivot, the right element is greater than pivot. Then the fast sorting algorithm is re-divided on the left and right sub-arrays. In the worst case, O (n*n) may occur, but the likelihood is very small.
3. Heap Sequencing
Sorting algorithm with time complexity O (N*LOGN)--merge sort, quick sort, heap sort