归并排序(分治思想)

#include 
using namespace std;
void sort(int*,int);
void sort(int *, int, int, int *);
void merge(int *,int,int,int ,int *);
void sort(int *arr,int len) {
	int *temp;
	temp = (int*)malloc(sizeof(int)*len);
	sort(arr,0,len - 1,temp);
}
void sort(int *arr, int left, int right, int *temp) {
	if (left < right) {
		int mid = (left + right) / 2;
           sort(arr, left, mid, temp); //分左边
		sort(arr, mid + 1, right, temp);//分右边
		merge(arr, left, mid, right, temp);//合并
	}
}
void merge(int *arr, int left, int mid, int right, int *temp) {
	int i = left;
	int j = mid + 1;
	int t = 0;
	while (i <= mid && j <= right) {
		if (arr[i] <= arr[j]) {
			temp[t++] = arr[i++];
		}
		else {
			temp[t++] = arr[j++];
		}
	}
	while (i <= mid) {
		temp[t++] = arr[i++];
	}
	while (j <= right) {
		temp[t++] = arr[j++];
	}
	t = 0;
	while (left <= right) {
		arr[left++] = temp[t++];
	}
}
int main() {
	int n;
	int arr[50001];
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &arr[i]);
	}
	sort(arr,n);
	return 0;
}

 

你可能感兴趣的:(归并排序(分治思想))