小说网 找小说 无限小说 烟雨红尘 幻想小说 酷文学 深夜书屋

基于visual Studio2013解决算法导论之002归并排序




题目

归并排序


解决代码及点评

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>

void PrintArr(int *pnArr, int nLen)
{
	for (int i = 0; i < nLen; i++)
	{
		printf("%d ", pnArr[i]);
	}
	printf("\n");
}
//合并两个数组
void Merge(int data[], int nLpos, int nRpos, int nRightEnd)
{
	int i;
	int k = nLpos;
	int nLeftEnd = nRpos;
	int nTmpPos = 0;
	int nLen = nRightEnd - nLpos + 1;
	int *pnArr = (int *)malloc(sizeof(int) * nLen);
	++nRpos;
	while (nLpos <= nLeftEnd && nRpos <= nRightEnd)
	{
		if (data[nLpos] <= data[nRpos])
		{
			pnArr[nTmpPos++] = data[nLpos++];
		}
		else
		{
			pnArr[nTmpPos++] = data[nRpos++];
		}
	}
	while (nLpos <= nLeftEnd)
	{
		pnArr[nTmpPos++] = data[nLpos++];
	}
	while (nRpos <= nRightEnd)
	{
		pnArr[nTmpPos++] = data[nRpos++];
	}

	nTmpPos = 0;
	for (i = k; i <= nRightEnd; i++)
	{
		data[i] = pnArr[nTmpPos++];
	}

	free(pnArr);
}
void MergeSort(int *pnArr, int nLeft, int nRight)
{
	if (nLeft > nRight)
	{
		return;
	}
	if (nRight > nLeft)
	{
		//1分解
		int nMid = (nLeft + nRight) / 2;

		//2解决
		MergeSort(pnArr, nLeft, nMid);
		MergeSort(pnArr, nMid + 1, nRight);

		//3合并
		Merge(pnArr, nLeft, nMid, nRight);
	}
}
int main()
{
	srand(time(NULL));
	int nArr[10];
	for (int i = 0; i < 10; i++)
	{
		nArr[i] = rand()%100;
	}

	printf("排序前:");
	PrintArr(nArr, 10);

	MergeSort(nArr, 0, 9);
	printf("排序后:");
	PrintArr(nArr, 10);

	system("pause");
	return 0;
}


代码下载及其运行

代码下载地址:http://download.csdn.net/detail/yincheng01/6858815

解压密码:c.itcast.cn


下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:

1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”


2)在下拉框中选择相应项目,项目名和博客编号一致

3)点击“本地Windows调试器”运行


程序运行结果









posted on 2014-01-17 14:56  牛栏山1  阅读(102)  评论(0编辑  收藏  举报

导航