//分治法实现归并排序 #include <iostream> using namespace std; #define SIZE 10 void merge(int array[],int first,int mid,int last) //合并 { int new_arr[SIZE],i,j,k=first; memset(new_arr,0,SIZE); for (i = first,j = mid + 1;(i <= mid)&&(j <= last);) { if(array[i] <= array[j]) new_arr[k++] = array[i++]; else new_arr[k++] = array[j++]; } if(i <= mid) for(;i <= mid;i++) new_arr[k++] = array[i]; if(j <= last) for(;j <= last;j++) new_arr[k++] = array[j]; for(int p = first;p <=last;p++) //将排好顺序的元素放回原数组【注意:p的范围为每个小分支中的元素,而非整个0到sizeof(arr)/sizeof(int)】 array[p]=new_arr[p]; } void merge_sort(int array[],int first,int last)//归并排序 { int mid = 0; if(first<last) { mid = (first + last)/2; merge_sort(array, first,mid); merge_sort(array, mid+1,last); merge(array,first,mid,last); } } int main() { int arr[SIZE]={9,3,5,6,8,7,0,2,1,4}; merge_sort(arr,0,9); for(int i = 0;i < SIZE;i++) cout << arr[i] << " "; cout << endl; return 0; }