设为首页 加入收藏

TOP

堆排序(非递归) (四)
2014-11-24 00:36:33 来源: 作者: 【 】 浏览:109
Tags:排序
{
break;
}
}
}
tmp = arr[0];
arr[0] = arr[num-1];
arr[num-1] = tmp;
}
}
测试代码:

#include
#include
#include <windows.h>

void HeapSort(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 = NULL;
arr = (int *)malloc(num * sizeof (int));
if (NULL == arr)
{
free(arr);
printf("内存分配失败,程序退出!\n");
getch();
return -1;
}

StartTime = GetTickCount();
for (i=0; i {
*(arr+i) = rand();
}
EndTime = GetTickCount();
printf("生成%u个随机数耗时:%ums\n", num, EndTime - StartTime);

StartTime = GetTickCount();
HeapSort(arr, num);
EndTime = GetTickCount();
printf("堆排序耗时:%ums\n", EndTime - StartTime);
ExamineArr(arr, num);//检查排序结果

free(arr);
getch();
return 0;
}

void HeapSort(int * const arr, const DWORD number)//堆排序
{
int tmp;
DWORD tmpIndex;
DWORD i=1;
DWORD num;
DWORD indexUp;
DWORD indexDown;
if (number < 2)
{
return;
}
indexUp = number-1;
if (0 != (indexUp%2))
{
tmpIndex = (indexUp - 1) / 2;
if (arr[indexUp] > arr[tmpIndex])
{
tmp = arr[indexUp];
arr[indexUp] = arr[tmpIndex];
arr[tmpIndex] = tmp;
}
indexUp--;
}
for (; indexUp>0; indexUp-=2)
{
tmpIndex = (indexUp / 2) - 1;
if (arr[indexUp-1] >= arr[indexUp])
{
if (arr[indexUp-1] > arr[tmpIndex])
{
tmp = arr[indexUp-1];
arr[indexUp-1] = arr[tmpIndex];
arr[tmpIndex] = tmp;
indexDown = indexUp-1;
}
else
{
continue;
}
}
else
{
if (arr[indexUp] > arr[tmpIndex])
{
tmp = arr[indexUp];
arr[indexUp] = arr[tmpIndex];
arr[tmpIndex] = tmp;
indexDown = indexUp;
}
else
{
continue;
}
}
while ((2*indexDown) < number)
{
tmpIndex = 2*indexDown +1;
if (arr[tmpIndex] >= arr[tmpIndex+1] || (tmpIndex+1 == number))
{
if (arr[tmpIndex] > arr[indexDown])
{
tmp = arr[indexDown];
arr[indexDown] = arr[tmpIndex];
arr[tmpIndex] = tmp;
indexDown = tmpIndex;
}
else
{
break;
}
}
else
{
if ((arr[tmpIndex+1] > arr[indexDown]) && (tmpIndex < number))
{
tmp = arr[indexDown];
arr[indexDown] = arr[tmpIndex+1];
arr[tmpIndex+1] = tmp;
indexDown = tmpIndex+1;
}
else
{
break;
}
}
}
}
tmp = arr[0];
arr[0] = arr[number-1

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇CSDN 讨论的找出缺失数的方法记录 下一篇归并排序(非递归)

评论

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