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

来源:互联网 发布:网络带来的方便 编辑:程序博客网 时间:2024/04/29 04:07



题目

归并排序


解决代码及点评

#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调试器”运行


程序运行结果








0 0
原创粉丝点击