堆排序:堆排序算法



# <stdlib.h>
# <stdio.h>
# <time.h>
# MAX_LENGTH 100
/*Show usage*/
void usage(char * prog)
{
prf(\"%s Usage:\\n\", prog);
prf(\"%s <the count of numbers to sort (should be less than 100)>\\n\", prog);
}
/*Generate and initialize the list*/
* generate_list( count)
{
i;
* list;
list = ( *)malloc(count*());
(list NULL)
{
perror(\"malloc\");
NULL;
}
/*Initialize the list with egers less than 100*/
srandom((unsigned )time(NULL));
for (i = 0; i < count ; i )
list[i] = random%100;
list;
}
/*Show the list*/
void show_list( * list, length)
{
i;
for(i = 0; i < length; i )
prf(\"%d \", list[i]);
prf(\"\\n\");
}
/*algorithm*/
void fix_heap( * list, h_size, root, k)
{
larger;
((2*root +1) > h_size)
list[root] = k;

{
((2*root +1) h_size)
{
larger = 2 * root +1;
}
(list[2*root+1] > list[2*root +2])
{
larger = 2 * root +1;
}

{
larger = 2 * root +2;
}
(k > list[larger])
list[root] = k;

{
list[root] = list[larger];
fix_heap(list, h_size, larger, k);
}
}
;
}
void build_heap( * list, length)
{
i;
for(i = (length+1)/2; i >= 0; i --)


fix_heap(list, length, i, list[i]);
;
}
void heap_sort( * list, length)
{
i;
build_heap(list, length - 1);
for(i = length -1; i >= 1; i --)
{
temp = list[i];
list[i] = list[0];
fix_heap(list, i -1, 0, temp);
}
}
( argc, char * argv)
{
length;
* list = NULL;
/*Deal with the arguments*/
(argc != 2)
{
usage(argv[0]);
exit(127);
}
length = atoi(argv[1]);
(!length || length > MAX_LENGTH)
{
usage(argv[0]);
exit(129);
}
list = generate_list(length);
(list NULL)
exit(128);

{
prf(\"Soruce list:\\n\");
show_list(list, length);
heap_sort(list, length);
prf(\"Ordered list:\\n\");
show_list(list, length);
}
free(list);
1;
}




Tags:  加密算法 c语言堆排序 堆排序c 堆排序

延伸阅读

最新评论

发表评论