归并排序算法

#include <iostream>

using namespace std;

int a[1001] = {0};
void merge(int a[], int left, int mid, int right){
	int i, j, k;
	int *B = new int[right - left + 1];
	i = left;
	j = mid + 1;
	k = 0;

	while (i <= mid && j <= right) {
		if (a[i] <= a[j])
			B[k++] = a[i++];
		else 
			B[k++] = a[j++];					
	}

	while (i <= mid)
		B[k++] = a[i++];
	while (j <= right)
		B[k++] = a[j++];
	for (i = left, k = 0; i <= right; i++)
		a[i] = B[k++];
	

}
void Mersort(int a[], int left, int right) {
	int mid = (left + right) >> 1;
	if (left == right)
		return;
	
	Mersort(a, left, mid);
	Mersort(a, mid + 1, right);
	merge(a, left, mid, right);
}
int main()
{
	int n;

	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];

	Mersort(a, 0, n - 1);

	for (int i = 0; i < n; i++)
		cout << a[i] << " ";

      return 0;
}
点赞