堆排序


#include <stdio.h>

void qSort(int* a, int head, int tail)
{
	int low,high,tmp;
	
	low = head;
	high = tail;
	tmp = a[low];

	if(low>=high) return;
	while(low<high)
	{
		while(a[high]>=tmp && low<high) high--;
		a[low] = a[high];
		while(a[low]<=tmp && low<high) low++;
		a[high] = a[low];
	}
	a[low] = tmp;

	qSort(a,head,low-1);
	qSort(a,low+1,tail);
}

void printArray(int* a, int head, int tail)
{
	int i=head;
	for(i=head;i<=tail;i++) printf("%d,",a[i]);
}

int binSearch(int s, int* a, int head, int tail)
{
	int mid,tmp;

	while(head<tail)
	{
		mid = (head+tail)/2;
		tmp = a[mid];
		if(s == tmp) return mid;
		if(s > tmp) head = mid+1;
		else tail = mid-1;
	}
	if(a[head] == s) return head;
	else return -1;
}

void heapAdjust(int* a, int p, int tail)
{	
	int i = p*2 + 1;
	int tmp;
	while(i<=tail)
	{		
		if(i<tail && a[i] < a[i+1]) i++;
		if(a[i] <= a[p]) break;
		else
		{
			tmp = a[i];
			a[i] = a[p];
			a[p] = tmp;
		}
		p = i;
		i = p*2 + 1;
	}
}

void heapSort(int* a, int tail)
{
	int i, tmp;

	for(i = (tail-1)/2; i>=0 ; i--)
	{
		heapAdjust(a,i,tail);
//		printArray(a,0,9);
//		printf("\n");
	}		
	for(i = tail; i>0 ; i--)
	{
		tmp = a[0];
		a[0] = a[i];
		a[i] = tmp;
//		printArray(a,0,9);
		heapAdjust(a,0,i-1);		
//		printf("\n");
	}
}

int main()
{
	int a[10] = {4,7,8,0,0,4,-1,5,7,8};
	int s = 8;
	int pos = -1;
//	qSort(a,0,9);
	heapSort(a,9);
	printArray(a,0,9);
	pos = binSearch(s,a,0,9);
	printf("\n%d\n",pos);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值