归并排序

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值