#include <iostream>
using namespace std;
void merge(int arr[], int first, int mid, int last){
int length = last - first + 1;
int i = first;
int j = mid + 1;
int k = 0;
int *p = new int[length];
while(i <= mid && j <= last){
if(arr[i] <= arr[j]){
p[k++] = arr[i++];
}else{
p[k++] = arr[j++];
}
}
while(i <= mid){
p[k++] = arr[i++];
}
while(j <= last){
p[k++] = arr[j++];
}
for(int i = 0; i < length; ++i){
arr[i + first] = p[i];
}
delete [] p;
p = NULL;
}
void mergeSort(int arr[], int first, int last){
int mid = (first + last) >> 1;
if(first == last){
return;
}else{
mergeSort(arr,first,mid);
mergeSort(arr,mid+1,last);
merge(arr,first,mid,last);
}
}
int main(){
int arr[] = {3,2,4,6,5,1,8,9};
int first = 0;
int last = 7;
mergeSort(arr, first, last);
for(int i = 0; i <= last; i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
归并排序
最新推荐文章于 2022-03-25 20:53:02 发布