归并排序

#include
#define N 200 
using namespace std;

void merge(int arr[], int left, int right){
	int mid = (left + right) >> 1;
	int l = left, r = mid+1, k=left;
	int _arr[right+1];
	
	while(l<=mid && r<=right){
		if(arr[l] <= arr[r])
			_arr[k++] = arr[l++];
		else
			_arr[k++] = arr[r++];	
	}
	
	while(l <= mid)
		_arr[k++] = arr[l++];
		
	while(r <= right)
		_arr[k++] = arr[r++];
		
	for(int i=left; i<=right; i++)
		arr[i] = _arr[i];
}


void sort(int arr[], int left, int right){
	if(left == right)
		return;
		
	int mid = (left + right) >> 1;
		
	sort(arr, left, mid);
	sort(arr, mid+1, right);
	merge(arr, left, right);
}


int main(){
	int n, arr[N];
	cout<<"请输入待排序数组大小(输入0退出):";
	cin>>n;
	
	while(n){
		cout<<"待排序数组:";
		for(int i=0; i<n; i++)
			cin>>arr[i];

		sort(arr, 0, n-1);
		
		cout<<"排序后数组:";
		for(int i=0; i<n; i++)
			cout<<arr[i]<<" ";
		cout<<endl<<endl<<"请输入待排序数组大小(输入0退出):";
		cin>>n;
	}
	
	return 0;
} 

你可能感兴趣的:(算法模板)