一个堆排序~

一个简单的堆排序,不知道有没有BUG。~~

= =

代码:

void Swap(DWORD& a, DWORD& b)
{
	if(a != b)
	{
		a = a^b;
		b = a^b;
		a = a^b;
	}
}

void AdjustHeap(DWORD* dwArray, int i, int nLenth)
{
	int nChild = i*2 + 1;
	while(nChild < nLenth)
	{
		//nChild指向较大的节点
		if(nChild < nLenth - 1 && dwArray[nChild] < dwArray[nChild+1])
			nChild++;
		if(dwArray[nChild] > dwArray[i])
		{
			Swap(dwArray[nChild], dwArray[i]);
			i = nChild;
			nChild = i*2 + 1;
		}
		else
			break;
	}

}

int BuildHeap(DWORD* dwArray, int nLenth)
{
	if(nLenth < 2)
		return TRUE;

	for(int i = nLenth/2-1; i >=0; i--)
	{
		AdjustHeap(dwArray, i, nLenth);
	}

	return TRUE;
}

int HeapSort(DWORD* dwArray, int nCount)
{
	BuildHeap(dwArray, nCount);
	for(int i = 0; i < nCount-1; i++)
	{
		AdjustHeap(dwArray, 0, nCount-i);
		Swap(dwArray[0], dwArray[nCount-i-1]);
	}

	return TRUE;
}

  

posted @ 2012-08-30 20:24  Kevin!=NULL  阅读(141)  评论(0编辑  收藏  举报