#include<iostream>
using namespace std;
void __merge(int arr[],int l,int mid,int r){
//auxiliary array
int *aux=new int[r-l+1];
for(int i=l;i<=r;i++) {
//copy datas
aux[i - l] = arr[i];
}
int i=l;
//int mid=l+(r-l)/2;
int j=mid+1;
for(int k=l;k<=r;k++){
//left branch out
if(i>mid){
arr[k]=aux[j-l];j++;
}
else if(j>r){
arr[k]=aux[i-l];i++;
}
else if(aux[i-l]<aux[j-l]){
arr[k]=aux[i-l];i++;
}
else {
arr[k]=aux[j-l];j++;
}
}
delete[] aux;
}
//arr[l...r]
void __mergeSort(int arr[],int l,int r){
//recurrence end condition
if(l>=r){
return;
}
int mid=(l+r)/2;
//divide
__mergeSort(arr,l,mid);
__mergeSort(arr,mid+1,r);
//merge(conquer)
__merge(arr,l,mid,r);
}
void merge(int arr[],int n){
__mergeSort(arr,0,n-1);
}
int main(){
int arr[]={3,2,4,1,8,7,9,6,5,0};
merge(arr,10);
for (int i = 0; i < 10; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
//merge from bottom to up
#include<iostream>
using namespace std;
void __merge(int arr[], int l, int mid, int r) {
//auxiliary array
int *aux = new int[r - l + 1];
for (int i = l; i <= r; i++) {
//copy datas
aux[i - l] = arr[i];
}
int i = l;
int j = mid + 1;
for (int k = l; k <= r; k++) {
if (j > r) {
arr[k] = aux[i - l];
i++;
}
else if (i > mid) {
arr[k] = aux[j - l];
j++;
}
else if (aux[i - l] < aux[j - l]) {
arr[k] = aux[i - l];
i++;
}
else {
arr[k] = aux[j - l];
j++;
}
}
delete[] aux;
}
void mergeBu(int arr[], int n) {
//divide
for (int sz = 1; sz < n; sz += sz) {
//merge arr[i...i+sz-1] arr[i+sz...i+sz+sz-1]
//if i+sz exists,i+sz-1<n-1
for (int i = 0; i + sz < n; i += sz + sz) {
__merge(arr, i, i + sz - 1, min(i + sz + sz - 1, n - 1));
}
}
}
int main() {
int arr[] = {3, 2, 4, 1, 8, 7, 5, 9, 0, 6};
mergeBu(arr, 10);
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}