Recursive merge sort

Foreword

The core of merge sort is actually merging two ordered arrays. I have always used the judgment of emptying, that is, judging who is the first of the two arrays and emptying the other one, but this is dealing with the boundary and the end It always feels a bit difficult when it comes to conditions. Then yesterday I saw the use of sentinels for merge operations in the introduction to algorithms. I thought the ideas were great, so I came to realize it.

Code

#include<iostream>
#include<vector>
using namespace std;

void myMerge(int a[], int p, int q, int r) {			//p ~ q, q+1 ~ r
	int n1 = q - p + 1;			//数组1的长度
	int n2 = r - q;				//数组2的长度
	vector<int> L(n1 + 1);
	vector<int>R(n2 + 1);
	for (int i = 0; i < n1; i++)
		L[i] = a[p + i];
	for (int i = 0; i < n2; i++)
		R[i] = a[q + 1 + i];
	L[n1] = 99999;			//假装这是无穷大的哨兵
	R[n2]  = 99999;
	int i = 0, j = 0;
	for (int k = 0; k < r - p + 1; k++) {        //注意这里的终止条件,因为只有r - p + 1个元素,所以只要移动这么多次即可判定合并完成
		if (L[i] > R[j]) {
			a[p + k] = R[j];
			j++;
		}
		else {
			a[p + k] = L[i];
			i++;
		}
	}
}

void mergeSort(int a[], int low, int high) {            //归并排序的递归题,很容易实现
	if (low == high)
		return;
	else{
		int mid = (low + high) / 2;
		mergeSort(a, low, mid);
		mergeSort(a, mid + 1, high);
		myMerge(a, low, mid, high);
		return;
	}
}

int main() {
	int a[] = { 3, 2, 4, 1, 7, 5, 6 };
	int b[] = { 1, 3, 5, 6, 2, 4, 7 };

	myMerge(b, 0, 3, 6);                //检验合并函数
	for (int i = 0; i < 7; i++)
		cout << b[i] <<" ";
	cout << endl;

	mergeSort(a, 0, 6);                //检验归并排序函数
	for (int i = 0; i < 7; i++)
		cout << a[i] << " ";
	cout << endl;
	return 0;
}

Guess you like

Origin www.cnblogs.com/Za-Ya-Hoo/p/12707659.html