算法复习 - 归并排序求解逆序数问题(分治)

题目描述:
在这里插入图片描述
解析:本题使用归并排序来求解逆序对数的问题,交换元素的次数正好就等于逆序数的个数。
代码:

#include
#include
#include
#include

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

void merge(vector<int>&a, int low, int high, int mid, int& count)
{
     
	vector<int>temp;
	int i = low, j = mid + 1;
	while (i <= mid and j <= high)
	{
     
		if (a[i] > a[j])
		{
     
			count++;
			temp.push_back(a[j++]);
		}
		else
			temp.push_back(a[i++]);
	}
	while (i <= mid)temp.push_back(a[i++]);
	while (j <= high)temp.push_back(a[j++]);
	for (auto i = 0; i < temp.size(); i++)a[low + i] = temp[i];
}

void mergeSort(vector<int>&a, int low, int high, int &count)
{
     
	if (low < high)
	{
     
		int mid = (low + high) / 2;
		mergeSort(a, low, mid, count);
		mergeSort(a, mid + 1, high, count);
		merge(a, low, high, mid, count);
	}
}

int main()
{
     
	vector<int>A = {
      3, 1, 4, 5, 2 };
	int count = 0;
	int low = 0, high = A.size() - 1;
	mergeSort(A, low, high, count);
	for (auto i = 0; i < A.size(); i++)cout << A[i] << "   ";
	cout << endl;
	cout << count << endl;
	return 0;
}

你可能感兴趣的:(算法作业,算法,分治算法,排序算法)