c++基础

归并排序

过程c++基础

递归实现


#include <iostream>  
using namespace std;
const int LEN = 10;
//将有二个有序数列a[first...mid]和a[mid...last]合并。  
void merge(int a[], int first, int mid, int last)
{
	int temp[10];
	int i = first, j = mid + 1;
	int m = mid, n = last;
	int k = 0;
	while (i <= m && j <= n)
	{
		if (a[i] <= a[j])
			temp[k++] = a[i++];
		else
			temp[k++] = a[j++];
	}
	while (i <= m)
		temp[k++] = a[i++];
	while (j <= n)
		temp[k++] = a[j++];
		
	for (i = 0; i < k; i++)
		a[first + i] = temp[i];
}
void merge_sort(int a[], int first, int last)
{
	if (first < last)
	{
		int mid = (first + last) / 2;
		merge_sort(a, first, mid);
		merge_sort(a, mid + 1, last);
		merge(a, first, mid, last);//算法核心
	}
}
int main()
{
	const int LEN = 10;
	int a[LEN] = { 23, 40, 45, 19, 12, 16, 90, 39, 87, 71 };
	for (int i = 0; i < LEN; ++i)
		cout << a[i] << " ";
	cout << endl;
	merge_sort(a, 0, LEN - 1);
	for (int i = 0; i < LEN; ++i)
		cout << a[i] << " ";
	cout << endl;
	return 0;
}