归并排序
Posted buaazhhx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序相关的知识,希望对你有一定的参考价值。
#include<iostream> #include<cstring> #include<vector> #include<algorithm> #include<map> using namespace std; void merge(int A[], int left,int mid,int right){ int p1 = left; int p2 = mid + 1; int temp[right-left+1]; int i = 0; while(p1 <= mid && p2 <= right){ temp[i++] = A[p1] > A[p2] ? A[p2++] : A[p1++]; } while(p1 <= mid){ temp[i++] = A[p1++]; } while(p2 <= right){ temp[i++] = A[p2++]; } for(int i = left; i <= right; i++){ A[i] = temp[i-left]; } } void sort(int A[], int left,int right) { if(left == right){ return; } int mid = left + ((right-left) >> 2); sort(A,left,mid); sort(A,mid+1,right); merge(A,left,mid,right); } int main(){ int a[] = {5,4,7,9,3,8,2,1}; sort(a,0,8); for(int i = 0; i < 8;i++){ cout<<a[i]<<" "; } return 0; }
以上是关于归并排序的主要内容,如果未能解决你的问题,请参考以下文章