废话不多说,直接show code:
#include<iostream>
using namespace std;
//归并过程
void merge(int *a, int start, int mid, int end){
int *temp = new int[end - start + 1];
int i = start;
int j = mid + 1;
int k = 0;
while(i<=mid && j<=end){
if(a[i] <= a[j]){
temp[k++] = a[i++];
}
else{
temp[k++] = a[j++];
}
}
while(i <= mid){
temp[k++] = a[i++];
}
while(j <= end){
temp[k++] = a[j++];
}
for(i = 0; i < k; i++){
a[start + i] = temp[i];
}
delete[] temp;
}
//递归过程
void mergeSort(int *a, int start, int end){
if(a==nullptr || start>=end) return;
int mid = (end + start) / 2;
mergeSort(a, start, mid);
mergeSort(a, mid+1, end);
merge(a, start, mid, end);
}
int main(){
int a[] = {2,5,1,6,0,3,7,9,4,8};
int length = sizeof(a)/sizeof(a[0]);
mergeSort(a, 0, length-1);
for(int i = 0; i < length; i++){
printf("%d ",a[i]);
}
printf("\n");
return 0;
}