Implementation of various sorting algorithms and sorting algorithms
1. Merge Sorting Algorithm:
Non-Recursive Implementation:
Void mergeSort (vector <int> & nums, vector <int> & tmpNums, int left, int right, int end) // right indicates the start of a data segment on the right, it can also be used to determine the end of a piece of data on the left, and the length of the array on the left is always greater than or equal to the length of the array on the right {int idx_left = left; int idx_right = right; int idx_total = left; while (idx_left <right & idx_right <= end) {if (nums [idx_left] <= nums [idx_right]) tmpNums [idx_total ++] = nums [idx_left ++]; elsetmpNums [idx_total ++] = nums [idx_right ++];} while (idx_left <right) tmpNums [idx_total ++] = nums [idx_left ++]; while (idx_right <= end) tmpNums [idx_total ++] = nums [idx_right ++]; idx_left = left; while (idx_left <= end) {nums [idx_left] = tmpNums [idx_left]; idx_left ++ ;}} void merge (vector <int> & nums, vector <int> & tmpNums) {int step = 1; int I; int n = nums. size (); while (step <n) {for (I = 0; I <= n-2 * step; I + = 2 * step) // note, here I <= n-2 * step is to ensure that the last pair of step Arrays can be correctly sorted {mergeSort (nums, tmpNums, I, I + step, I + 2 * step-1);} if (I <n-step) mergeSort (nums, tmpNums, I, I + step, n-1 ); // For the end cannot be exactly a step length, to be processed separately, and ensure that the last parameter is n-1step * = 2 ;}}
Recursive Implementation:
void mergeSort(vector<int> & nums, vector<int> &tmpNums, int left, int right, int end){int idx_left=left;int idx_right=right;int idx_total=left;while(idx_left<right && idx_right<=end){if(nums[idx_left]<=nums[idx_right])tmpNums[idx_total++]=nums[idx_left++];elsetmpNums[idx_total++]=nums[idx_right++];}while(idx_left<right)tmpNums[idx_total++]=nums[idx_left++];while(idx_right<=end)tmpNums[idx_total++]=nums[idx_right++];idx_left=left;while(idx_left<=end){nums[idx_left]=tmpNums[idx_left];idx_left++;}}void merge(vector<int> & nums, vector<int> & tmpNums, int left, int right){if(left<right){int mid=(left+right)/2;merge(nums, tmpNums, left, mid);merge(nums, tmpNums, mid+1, right);mergeSort(nums, tmpNums, left, mid+1, right);}}