归并排序

我认为归并排序就是先把问题缩小化之后,分成多个集合,每一个集合进行排序,排成一个有序的序列,之后把集合合并一些,在进行排序,直到成为一个大集合为止。


归并排序动画演示,请点

void merge_sort (int *A, int x, int y, int *T) {
	if (y-x > 1) {
		int m = x + (y-x) /2;
		int p = x, q = m, i = x;
		merge_sort (A, x, m, T);
		merge_sort (A, m, y, T);
		while (p < m || q < y) {
			if (q >= y || (p < m && A[p] <= A[q])) T[i++] = A[p++];
			else T[i++] = A[q++];
		}
		for (i = x;i < y;i++) A[i] = T[i];
	}
}

在刘汝佳的算法入门经典中看到的,感觉十分的简练。


我还在网上看到这样的一种归并算法,感觉十分的墨迹,和数据结构高一凡写的差不多。


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void mergearray(int a[], int first, int mid, int last, int temp[])
{
	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 mergesort(int a[], int first, int last, int temp[])
{
	if (first < last)
	{
		int mid = (first + last) / 2;
		mergesort(a, first, mid, temp);   
		mergesort(a, mid + 1, last, temp); 
		mergearray(a, first, mid, last, temp); 
	}
}

bool MergeSort(int a[], int n)
{
	int *p = new int[n];
	if (p == NULL)
		return false;
	mergesort(a, 0, n - 1, p);
	delete[] p;
	return true;
}

int main (void) {
	int num;
	int arr[100];
	while (scanf ("%d", &num) != EOF) {
		for (int i = 0;i < num;i++) {
			scanf ("%d", &arr[i]);
		}
		MergeSort (arr, num);
		for (int i = 0;i < num;i++) {
			printf ("%d ", arr[i]);
		}
		printf ("\n");
		
	}
	return 0;
}
点赞