欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

归并排序

程序员文章站 2022-05-10 15:12:07
...

归并排序

归并排序有分和合两个部分

void Sort(int* a, int left1, int right1, int left2, int right2) {
	int tmp[MAXN];
	int mark1 = left1, mark2 = left2;
	int index = left1;
	while (mark1 <= right1 && mark2 <= right2) {
		if (a[mark1] <= a[mark2]) {
			tmp[index++] = a[mark1];
			mark1++;
		}
		else {
			tmp[index++] = a[mark2];
			mark2++;
		}
	}
	while (mark1 <= right1) {
		tmp[index++] = a[mark1++];

	}
	while (mark2 <= right2) {
		tmp[index++] = a[mark2++];
	}
	for (int i = left1; i <= right2; i++) a[i] = tmp[i];
}
void merge_sort(int* a, int left, int right) {
	if (left == right) return;
	int mid = (left + right) >> 1;
	// Sort(a, left, mid, mid + 1, right);
	merge_sort(a, left, mid);
	merge_sort(a, mid + 1, right);
	Sort(a, left, mid, mid + 1, right);
}
相关标签: 归并排序 排序