归并排序(C语言)

#include 
#include 
#include 
#define NUM 80000
#define RANGE 80000

void merge_sort(int* arr, int l, int n) {
	if (n - l <= 1) return;
	int mid = (l + n) / 2;
	merge_sort(arr, l, mid);
	merge_sort(arr, mid, n);
	int* temp = (int*)malloc(sizeof(int) * (n - l));
	int p1 = l, p2 = mid, k = 0;
	while (p1 < mid || p2 < n) {
		if (p2 == n || (p1 < mid && arr[p1] <= arr[p2])) {
			temp[k++] = arr[p1++];
		}
		else temp[k++] = arr[p2++];
	}
	for (int i = l; i < n; i++) arr[i] = temp[i - l];
	free(temp);
	return;
}

int main() {
	int arr[NUM] = { 0 };
	srand(time(0));
	for (int i = 0; i < NUM; i++) {
		arr[i] = rand() % RANGE;
	}
	merge_sort(arr, 0, NUM);
	for (int i = 0; i < NUM; i++) {
		printf("%d ", arr[i]);
	}
	return 0;
}

你可能感兴趣的:(排序,算法,排序算法,数据结构)