设为首页 加入收藏

TOP

归并排序(非递归) (一)
2014-11-24 00:36:32 来源: 作者: 【 】 浏览:79
Tags:归并 排序

以下代码经测试,排序5000000(五千万)int型数据没有问题!

第一个参数是数组首地址
第二个参数是数组元素个数
void MergeSort(int * const arr, const DWORD number)//归并排序
{
DWORD i;
DWORD index1, index2;//将数组分为两个,分别作为两个数组第一个元素的下标
DWORD tmpIndex1, tmpIndex2;//分别指向两个数组中的元素相对于index1、index2的步进
DWORD step;//步进
int *tmpArr = NULL;
if (number < 2)
{
return;
}
tmpArr = (int *)malloc(number*sizeof (int));
if (NULL == tmpArr)
{
printf("分配缓存出错!\n");
getch();
return;
}
for (step=1; step {
index1 = 0;
index2 = index1 + step;
tmpIndex1 = 0;
tmpIndex2 = 0;
i = 0;
while ((index2+tmpIndex2) < number)
{
while ((tmpIndex1 < step) && (tmpIndex2 < step) && ((index2+tmpIndex2) < number))
{
if (arr[index1+tmpIndex1] <= arr[index2+tmpIndex2])
{
tmpArr[i] = arr[index1+tmpIndex1];
tmpIndex1++;
}
else
{
tmpArr[i] = arr[index2+tmpIndex2];
tmpIndex2++;
}
i++;
}
while (tmpIndex1 {
tmpArr[i++] = arr[index1+tmpIndex1];
tmpIndex1++;
}
while ((tmpIndex2 {
tmpArr[i++] = arr[index2+tmpIndex2];
tmpIndex2++;
}
index1 = index1 + 2*step;
index2 = index2 + 2*step;
tmpIndex1 = 0;
tmpIndex2 = 0;
}
memcpy(arr, tmpArr, number*sizeof (int));
}
free(tmpArr);
}
void MergeSort(int * const arr, const DWORD number)//归并排序
{
DWORD i;
DWORD index1, index2;//将数组分为两个,分别作为两个数组第一个元素的下标
DWORD tmpIndex1, tmpIndex2;//分别指向两个数组中的元素相对于index1、index2的步进
DWORD step;//步进
int *tmpArr = NULL;
if (number < 2)
{
return;
}
tmpArr = (int *)malloc(number*sizeof (int));
if (NULL == tmpArr)
{
printf("分配缓存出错!\n");
getch();
return;
}
for (step=1; step {
index1 = 0;
index2 = index1 + step;
tmpIndex1 = 0;
tmpIndex2 = 0;
i = 0;
while ((index2+tmpIndex2) < number)
{
while ((tmpIndex1 < step) && (tmpIndex2 < step) && ((index2+tmpIndex2) < number))
{
if (arr[index1+tmpIndex1] <= arr[index2+tmpIndex2])
{
tmpArr[i] = arr[index1+tmpIndex1];
tmpIndex1++;
}
else
{
tmpArr[i] = arr[index2+tmpIndex2];
tmpIndex2++;
}
i++;
}
while (tmpIndex1 {
tmpArr[i++] = arr[index1+tmpIndex1];
tmpIndex1++;
}
while ((tmpIndex2 {
tmpArr[i++] = arr[index2+tmpIndex2];
tmpIndex2++;
}
index1 = index1 + 2*step;
index2 = index2 + 2*step;
tmpIndex1 = 0;
tmpIndex2 = 0;
}
memcpy(arr, tmpArr, number*sizeof (int));
}
free(tmpArr);
}

测试代码:

#include
#include
#include <windows.h>

void MergeSort(int * const arr, const DWORD number);//归并排序
void ExamineArr(const int * const arr, DWORD number);//检查排序结果

int main(int argc, char *argv[])
{
DWORD StartTime, EndTime;
DWORD i;
DWORD num = 50000000;
int *arr = N

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇堆排序(非递归) 下一篇Beej’s Guide Network to Progra..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: