首页 > 代码库 > 二路归并排序
二路归并排序
#include <iostream>using namespace std;void merge(int* ptr,int first, int mid, int last){ int len = last - first + 1; int *temp = new int[len]; int i = first, j = mid + 1, k = 0; while(i <= mid && j <= last) { if(ptr[i] <= ptr[j]) { temp[k++] = ptr[i++]; } else { temp[k++] = ptr[j++]; } } while(i<=mid) { temp[k++] = ptr[i++]; } while(j<=last) { temp[k++] = ptr[j++]; } for( k =0;k < len; ++k) { ptr[first++] = temp[k]; } delete [] temp;}void mergeSort(int *ptr,int first,int last){ if (first < last) { int mid = (first + last)/2; mergeSort(ptr,first,mid); mergeSort(ptr,mid+1,last); merge(ptr,first,mid,last); }}int main(){ int a[] = {2,23,45,1,8,2,0}; for(int i =0; i <= 6; ++i) { std::cout << a[i] << " "; } cout << endl; mergeSort(a,0,6); for(int i =0; i <= 6; ++i) { std::cout << a[i] << " "; } std::cout << std::endl; return 0;}
二路归并排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。