1. 归并排序算法:
非递归实现:
void mergeSort(vector<int> & nums, vector<int> &tmpNums, int left, int right, int end)//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++]; else tmpNums[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)//注意,这里i<=n-2*step是因为要保证最后的一对step数组能够正确排序 { mergeSort(nums, tmpNums, i, i+step, i+2*step-1); } if(i<n-step) mergeSort(nums, tmpNums, i, i+step, n-1);//对于最后不能正好是一对step长度的情况,要单独处理,且保证最后一个参数为n-1 step*=2; } }递归实现方式:
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++]; else tmpNums[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); } }
原文地址:http://blog.csdn.net/jisuanji_wjfioj/article/details/46490373