归并排序算法

基本思想:

S1:把当前序列几乎平均分成两份

S2:递归处理左边,保证左半边有序

S3:递归处理右边,保证右半边有序

S4:把两边归并。

/**************归并算法模板**************/
void merge(int *a, int *temp, int first, int mid, int last){
	int i = first, j = mid + 1;
	int index = first;
	while (i <= mid&&j <= last){
		if (a[i] > a[j]){
			temp[index++] = a[j];
			j++;
		}
		else{
			temp[index++] = a[i];
			i++;
		}
	}
	while (i <= mid)
		temp[index++] = a[i++];
	while (j <= last)
		temp[index++] = a[j++];
	for (int i = first; i <= last; i++)
		a[i] = temp[i];
}
void mergeSort(int *a, int *temp, int first, int last){
	if (first >= last)
		return;
	int mid = (first + last) / 2;
	mergeSort(a, temp, first, mid);
	mergeSort(a, temp, mid + 1, last);
	merge(a, temp, first, mid, last);
}


你可能感兴趣的:(归并排序算法)