C语言实现归并排序

int brr[100] = {0};//辅助数组
void merge(int arr[], int low,int mid,int high) {
	int i = low;//遍历左子列
	int j = mid+1;//遍历右子列
	int k = 0;
	for(k=0;k<=high;k++){//先将arr的元素全部复制到辅助数组brr中
		brr[k] = arr[k];
	}
	k = i;
	while (i<= mid&&j <= high) {
		if (brr[i] < brr[j]) {
			arr[k] = brr[i];
			k++;
			i++;
		}
		else {
			arr[k] = brr[j];
			k++;
			j++;
		}
	}
	//一个子列遍历结束,把另一个子列剩余的接上去
	while (i <= mid) {
		arr[k] = brr[i];
		i++;
		k++;
	}
	while (j <= high) {
		arr[k] = brr[j];
		j++;
		k++;
	}
}
void mergeSort(int arr[], int low, int high) {
	if (low < high) {
		int mid = (low + high) / 2;
		mergeSort(arr, low, mid);//归并左子列
		mergeSort(arr, mid+1, high);//归并右子列
		merge(arr, low, mid,high);
	}
}
int main() {
	int arr[10] = { 3,5,2,9,1,4,8,6,10,7 };
	mergeSort(arr,0,9);
	for (int i = 0;i < 10;i++) {
		printf("%d ", arr[i]);
	}
	return 0;
}

C语言实现归并排序_第1张图片

你可能感兴趣的:(数据结构代码汇总,c语言,算法,归并排序)