二分归并排序:对n个不同的数构成的数组A[1…n]进行排序,其中n=2^k
-
核心算法及图解
其算法核心思想就是把一个大问题在不改变前提的条件下拆分为若干个小问题,实现分而治之;
以数组arr[8] = {7, 3, 10, 4, 19, 0, 13, 9}为例
复杂度
代码
#include <bits/stdc++.h>
using namespace std;
int mergearray(int a[],int left,int mid,int right,int temp[]){
int i=mid+1,k=0,l=left;
while(left <= mid && i <= right){
if(a[left]<=a[i])
temp[k++] = a[left++];
else
temp[k++] = a[i++];
}
while(left <= mid)
temp[k++] = a[left++];
while(i <= right)
temp[k++] = a[i++];
for(int j=0;j<k;j++){
a[l+j] = temp[j];
}
}
int mergesort(int a[],int l,int r,int temp[]){
if(l<r){
int mid = (l+r)/2;
mergesort(a,l,mid,temp);
mergesort(a,mid+1,r,temp);
mergearray(a,l,mid,r,temp);
}
}
int main(){
int *temp = (int *)malloc(8*sizeof(int));
int arr[8]={7,3,10,4,19,0,13,9};
mergesort(arr,0,7,temp);
for(int i=0;i<8;i++)
cout<<arr[i]<<" ";
}