// Test.cpp : Defines the entry point for the console application.
//
#include <stdafx.h>
#include <iostream>
#include <string.h>
using namespace std;
void merge(int* a, int start, int mid, int end, int* c){
int i = start;
int k = 0;
int j = mid + 1;
while (i <= mid&&j <= end)
{
if (a[i] < a[j]){
c[k++] = a[i++];
}
else{
c[k++] = a[j++];
}
}
while (i <= mid){
c[k++] = a[i++];
}
while (j <= end){
c[k++] = a[j++];
}
memcpy(a + start, c, sizeof(int)*k);
}
void merge_sort(int* a, int start,int end,int* out){
if (start < end){
int mid = (start + end) / 2;
merge_sort(a, start, mid, out);
merge_sort(a, mid + 1, end, out);
merge(a, start, mid, end, out);
}
}
int main(int argc, char *argv[])
{
#if 0//测试合并函数
int a[] = { -2, -4, 0, 4, 5, 7, 8, 9 };
int b[] = { 2, 4, 4, 5, 6, 9, 20, 56 };
int asize = sizeof(a) / sizeof(int);
int bsize = sizeof(b) / sizeof(int);
int csize = asize+bsize;
int* c = (int*)malloc(sizeof(int)*csize);
memcpy(c, a, sizeof(a));
memcpy(c+asize, b, sizeof(b));
if (!c){ return -1; }
int* d = (int*)malloc(sizeof(int)*csize);
merge(c, 0, (0 + csize-1) / 2, csize-1, d);
int i = 0;
int*p = d;
while (i < csize){
printf("%d ", d[i]);
i++;
}
if (c)free(c);
if (d)free(d);
#else
//测试归并排序
int f[] = { 9, 2, 0, 1, 4, 4, -2, -4, 0, 4, 5, 7, 8, 9, 3, 5, 6, 9, 20, 56 };
int fsize = sizeof(f) / sizeof(int);
int* out = (int*)malloc(sizeof(f));
merge_sort(f, 0,fsize-1,out);
int j = 0;
printf("\n");
while (j < fsize){
printf("%d ", out[j++]);
}
printf("\n");
if (out)free(out);
#endif
return 0;
}
归并排序
最新推荐文章于 2024-08-12 19:32:44 发布