堆排序(代码1)

#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;
}




*/

 

posted @ 2014-09-28 11:23  yyxayz  阅读(133)  评论(0编辑  收藏  举报