合并排序

#include "stdafx.h" #include <iostream> #include <algorithm> #include <iterator> using namespace std; void MergeSort(int arr[], int low, int high); void Merge(int arr[], int low, int midle, int high); int main() { const int N = 10; int arr[N]; for(int i=0; i<N; i++) arr[i] = rand()%30; cout<<"原数组:"<<endl; copy(arr, arr+N, ostream_iterator<int>(cout, " ")); cout<<endl; MergeSort(arr, 0, N); cout<<"排序后:"<<endl; copy(arr, arr+N, ostream_iterator<int>(cout, " ")); cout<<endl; } void MergeSort(int arr[], int low, int high) { int mid = 0; if(low < high)//不是while是if,为这个错误找了好几天 { mid = (low + high) / 2; MergeSort(arr, low, mid); MergeSort(arr, mid+1, high); Merge(arr, low, mid, high); } } void Merge(int arr[], int low, int mid, int high) { int n = high - low; int *temp = new int[n];//存放合并元素的临时数组 int i = low; int j = mid; int k = 0; while((i<mid) && (j<high)) { if( arr[i] < arr[j]) { temp[k] = arr[i]; ++i; } else { temp[k] = arr[j]; ++j; } ++k; } while(i < mid) temp[k++] = arr[i++]; while(j < high) temp[k++] = arr[j++]; for(k=low; k<high; k++) //重新拷贝回去 { arr[k] = temp[k - low]; } delete []temp; }  

你可能感兴趣的:(合并排序)