首页 > 代码库 > 归并排序——最省时的排序
归并排序——最省时的排序
/*因为归并排序至于O(n)的复杂度所以省时*/#include<iostream>#include<stdio.h>#include<string.h>#include<string>#include<algorithm>#include<vector>#include<map>#define N 100010#define MAXN 100010using namespace std;//将有二个有序数列a[first...mid]和a[mid...last]合并。void mergearray(int a[], int first, int mid, int last, int temp[]){ int i = first, j = mid + 1; int m = mid, n = last; int k = 0; while (i <= m && j <= n) { if (a[i] <= a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= m) temp[k++] = a[i++]; while (j <= n) temp[k++] = a[j++]; for (i = 0; i < k; i++) a[first + i] = temp[i];}void mergesort(int a[], int first, int last, int temp[]){ if (first < last) { int mid = (first + last) / 2; mergesort(a, first, mid, temp); //左边有序 mergesort(a, mid + 1, last, temp); //右边有序 mergearray(a, first, mid, last, temp); //再将二个有序数列合并 }}bool MergeSort(int a[], int n){ int *p = new int[n]; if (p == NULL) return false; mergesort(a, 0, n - 1, p); delete[] p; return true;}int main(){ //freopen("C:\\Users\\acer\\Desktop\\in.txt","r",stdin); int cur1[]={1,4,7,8,5,2,3,6,9,0}; int cur2[12]; mergesort(cur1, 0, 9, cur2); for(int i=0;i<10;i++) cout<<cur2[i]<<" "; cout<<endl; return 0;}
归并排序——最省时的排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。