好吧,跟 http://blog.csdn.net/morewindows/article/details/6678165 差不多是一样的。。
#define ARR_SIZE 30
#include <limits.h>
#include <stdlib.h>
#include <assert.h>
void merge(int *arr, int first, int mid, int last, int *temp);
void print(int *arr);
void mergeSort(int *arr, int first, int last, int *temp){
int mid = 0;
if(first >= last){
return;
} else {
mid = (first + last) / 2;
mergeSort(arr, first, mid, temp);
mergeSort(arr, mid + 1, last, temp);
merge(arr, first, mid, last, temp);
}
}
void merge(int *arr, int first, int mid, int last, int *temp){
int pos = first;
int pos1 = first;
int pos2 = mid + 1;
while(pos1 <= mid && pos2 <= last){
if(temp[pos1] <= temp[pos2]){
arr[pos++] = temp[pos1++];
} else {
arr[pos++] = temp[pos2++];
}
}
if(pos1 > mid){ //pos2 does not exceed last
while(pos2 <= last){
arr[pos++] = temp[pos2++];
}
} else { //pos1 does not exceed mid
while(pos1 <= mid){
arr[pos++] = temp[pos1++];
}
}
assert(pos == last + 1);
//copy sorted arr to temp
for(pos = first; pos <= last; ++pos){
temp[pos] = arr[pos];
}
}
int main(){
int index;
int arr[ARR_SIZE];
int temp[ARR_SIZE];
int num = 0;
for(index = 0; index < ARR_SIZE; ++index){
num = rand();
arr[index] = temp[index] = 100 * ((float)num / RAND_MAX);
}
printf("elements before sort:\n");
print(arr);
mergeSort(arr, 0, ARR_SIZE - 1, temp);
printf("elements after sort:\n");
print(arr);
return 0;
}
void print(int *arr){
int index;
for(index = 0; index < ARR_SIZE; ++index){
printf("%d ", arr[index]);
}
printf("\n");
}