归并排序C++实现及求逆序对的个数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序C++实现及求逆序对的个数相关的知识,希望对你有一定的参考价值。
1.归并排序的递归实现:
#include<iostream> #include<vector> #include<string> #include<strstream> #include<algorithm> #include<unordered_map> using namespace std; void MergeSort(vector<int>& nums, vector<int> ©, int start, int end) { if (start == end) { copy[start] = nums[start]; return; } int len = (end - start) / 2; MergeSort(nums, copy, start, start + len); MergeSort(nums, copy, start + len + 1, end); int i = start, j = start + len + 1, index = start; while (i <= start + len && j <= end) { if (nums[i] < nums[j]) { copy[index] = nums[i]; i++; } else { copy[index] = copy[j]; j++; } index++; } while (i <= start + len)//如果前半段有剩余则复制到copy数组中 { copy[index] = nums[i]; ++i; ++index; } while (j <= end)//如果后半段有剩余则复制到copy数组中 { copy[index] = nums[j]; ++j; ++index; } for (int i = start;i <= end;i++)//此时copy数组已经有序,将其复制到原数组中 nums[i] = copy[i]; } int main() { int a[8] = { 8, 4 ,7,0,3,5,9,1 }; vector<int> nums(a, a + 8); int len = nums.size(); vector<int> copy(len); MergeSort(nums, copy, 0, len - 1); for (auto e : nums) cout << e << " "; cout << endl; for (auto e : copy) cout << e << " "; cout << endl; return 0; }
2. 求逆序对的个数
只需将归并排序的算法稍微修改一下即可
#include<iostream> #include<vector> #include<string> #include<strstream> #include<algorithm> #include<unordered_map> using namespace std; int MergeSort(vector<int>& nums, vector<int> ©, int start, int end) { if (start == end) { copy[start] = nums[start]; return 0; } int len = (end - start) / 2; int left = MergeSort(nums, copy, start, start + len); int right = MergeSort(nums, copy, start + len + 1, end); int i = start, j = start + len + 1, index = start; int cnt = 0; while (i <= start + len && j <= end) { if (nums[i] < nums[j]) { copy[index] = nums[i]; i++; } else { copy[index] = copy[j]; j++; cnt += start + len - i + 1;//次数统计逆序对 } index++; } while (i <= start + len)//如果前半段有剩余则复制到copy数组中 { copy[index] = nums[i]; ++i; ++index; } while (j <= end)//如果后半段有剩余则复制到copy数组中 { copy[index] = nums[j]; ++j; ++index; } for (int i = start;i <= end;i++)//此时copy数组已经有序,将其复制到原数组中 nums[i] = copy[i]; return left + right + cnt; } int main() { int a[8] = { 7,5,6,4 }; vector<int> nums(a, a + 4); int len = nums.size(); vector<int> copy(len); cout << "kkk "<<MergeSort(nums, copy, 0, len - 1) << endl; for (auto e : nums) cout << e << " "; cout << endl; for (auto e : copy) cout << e << " "; cout << endl; return 0; }
以上是关于归并排序C++实现及求逆序对的个数的主要内容,如果未能解决你的问题,请参考以下文章