码迷,mamicode.com
首页 > 其他好文 > 详细

堆排序(代码1)

时间:2014-09-28 13:18:02      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   for   sp   div   c   log   代码   

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

void build_heap(int data[], int);
void adjust_heap(int data[], int);
void heap_sort(int data[], int);
int sub_max_heap(int data[], int, int);

int main(int argc, char *argv[])
{
	int i;
	int data[12] = {6, 10, 3, 5, 12, 8, 4, 23, 1, 2, 9, 7 };

	heap_sort(data, 12);

	for (i = 0; i < 12; ++i)
	{
		printf("%d ", data[i]);
	}

	printf("\n");
	return 0;
}

void heap_sort(int data[], int num)
{
	int i = 1;
	build_heap(data, num);

	for (i = 1; i < num; ++i)
	{
		int temp;
		temp = data[0];
		data[0] = data[num - i];
		data[num - i] = temp;

		adjust_heap(data, num - i);	
	}

}


void build_heap(int data[], int num)
{
	int i, k, p;

	for (i = num / 2 - 1; i >= 0; --i)
	{
		k = sub_max_heap(data, num, i);

		while (2 * k + 1 < num)
		{
			p = k;
			k = sub_max_heap(data, num, p);
		}
	}

}


void adjust_heap(int data[], int num)
{
	int temp;
	int k, p;

	k = 0;
	while(2 * k + 1 < num)
	{
		p = k;
		k = sub_max_heap(data, num, p);
	}


}

int sub_max_heap(int data[], int num, int i)
{
	int k;

	if (2 * i + 2 <= num - 1 && data[2 * i + 1] > data[2 * i + 2])
		k = 2 * i + 1;
	else if (2 * i + 2 <= num - 1)
		k = 2 * i + 2;
	else
		k = 2 * i + 1;

	if (data[k] > data[i])
	{
		int temp;
		temp = data[k];
		data[k] = data[i];
		data[i] = temp;
	}
	
	return k;

}
/*
int sub_max_heap(int data[], int num, int i)
{
	int largest;
	int l, r;

	l = 2 * i + 1;
	r = 2 * i + 2;
	
	if (l <= num - 1 && data[l] > data[i])
		largest = l;
	else
		largest = i;
	
	if (r <= num - 1 && data[r] > data[largest])
		largest = r;
	if (largest != i)
	{
		int temp;
		temp = data[i];
		data[i] = data[largest];
		data[largest] = temp;
	}

	return largest;
}




*/

 

堆排序(代码1)

标签:blog   io   ar   for   sp   div   c   log   代码   

原文地址:http://www.cnblogs.com/yyxayz/p/3997957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!