#include <iostream>
using namespace std;
/*
*把数组从中间分为2部分,分别将两部分排好序后,调用merge将2个有序序列合并成1个有序序列
*
*/
void merge(int* arr, int start, int mid, int end){
int* p = new int[1000];
int* q = new int[1000];
for(int i = start; i <= mid; i++){
p[i] = arr[i];
}
for(int j = mid + 1; j <= end; j++){
q[j] = arr[j];
}
int i = start, j = mid + 1;
int pos = start;
while(i <= mid || j <= end){
if(i > mid){ //处理一方到达尽头
arr[pos++] = q[j++];
continue;
}
if(j > end){
arr[pos++] = p[i++];
continue;
}
if(p[i] <= q[j]){
arr[pos++] = p[i++];
}
else if(p[i] > q[j]){
arr[pos++] = q[j++];
}
}
delete[] p;
delete[] q;
}
void merge_sort(int* arr, int start, int end){
if(start >= end) return; //递归出口
int mid = start + (end - start) / 2;
merge_sort(arr, start, mid);
merge_sort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
int main(){
int arr[] = { 3, 5, 6 ,8, 2, 1, 9, 4, 0, 7};
merge_sort(arr, 0, 9);
for(int i = 0; i < 10; i++){
cout << arr[i] << " ";
}
system("PAUSE");
}
01-28
08-16