归并排序(递归实现)

#include

int merge(int data[], int low, int mid, int high, int space[]);
int merge_sort(int data[], int low, int high, int space[]);
int MergeSort(int arr[], int length);

int main()
{
     
	int arr[20];
	for (int i = 0; i < 20; i++)
	{
     
		arr[i] = 20 - i;
	}
	MergeSort(arr, 20);
	for (int i = 0; i < 20; i++)
	{
     
		printf("%4d ", arr[i]);
		if ((i + 1) % 10 == 0){
     
			puts("");
		}
	}
	return 0;
}

int merge(int data[], int low, int mid, int high, int temp_space[])
{
     
	int i = low, j = mid + 1;
	int k = low;
	while (i <= mid && j <= high)
	{
     
		if (data[i] <= data[j]){
     
			temp_space[k++] = data[i++];
		}
		else{
     
			temp_space[k++] = data[j++];
		}
	}
	while (i <= mid)
	{
     
		temp_space[k++] = data[i++];
	}
	while (j <= high)
	{
     
		temp_space[k++] = data[j++];
	}
	for (int i = low; i <= high; i++)
		data[i] = temp_space[i];
	return 0;
}

int merge_sort(int data[], int low, int high, int temp_space[])
{
     
	if (low == high){
     
		return 0;
	}
	else{
     
		int mid = (low + high) / 2;
		merge_sort(data, low, mid, temp_space);
		merge_sort(data, mid + 1, high, temp_space);
		merge(data, low, mid, high, temp_space);
	}
	return 0;
}

int MergeSort(int arr[], int length)
{
     
	int* temp_space = new int[length];
	merge_sort(arr, 0, length - 1, temp_space);
	delete temp_space;
	return 0;
}

你可能感兴趣的:(数据结构与算法,C/C++)