25.归并排序

来源:互联网 发布:闻道网络有多少员工 编辑:程序博客网 时间:2024/06/07 08:24

2路归并排序,代码实现:

#include<iostream>#include<cstring>#include<cstdio>using namespace std;void MergeArray(int s, int e, int mid, int a[], int temp[]){int num = 0, t1 = s, t2 = mid+1;while(t1<=mid && t2<=e){if(a[t1] < a[t2]){temp[num++] = a[t1];++t1;}else{temp[num++] = a[t2];++t2;}}while(t1 <= mid){temp[num++] = a[t1];++t1;}while(t2 <= e){temp[num++] = a[t2];++t2;}for(int i=0; i<num; ++i)a[i+s] = temp[i];}void MergeSort(int a[], int s, int e, int temp[]){if(s < e){int mid = (s+e) >> 1;MergeSort(a, s, mid, temp);    MergeSort(a, mid+1, e, temp);MergeArray(s, e, mid, a, temp);}}void solve(int a[], int n){if(n <= 0) return;int *temp = new int[n];if(temp == NULL)return ;MergeSort(a, 0, n-1, temp);delete []temp;}int main(){int a[1005], n, i;while(scanf("%d", &n) != EOF){for(i=0; i<n; ++i)scanf("%d",&a[i]);solve(a, n);for(i=0; i<n; ++i)printf("%d ",a[i]);printf("\n");}return 0;}


0 0
原创粉丝点击