Max heap with problems

Source: Internet
Author: User

I just read the introduction to algorithms. I wrote code and the test was wrong... in the morning, I don't have time. I'll go to work right away. I'll post it here. I'll take a look at it later:

int GetParentIndex(int i){return (i+1)/2-1;}int GetLeftChild(int i){return 2*i+1;}int GetRightChild(int i){return 2*(i+1);}void MaxHeapfy(int* aArr,int aIndex,int aHeapSize){int lMaxIndex = aIndex;if (GetLeftChild(aIndex) < aHeapSize && aArr[GetLeftChild(aIndex)] > aArr[aIndex]){lMaxIndex = GetLeftChild(aIndex);}if (GetRightChild(aIndex) < aHeapSize && aArr[GetRightChild(aIndex)] > aArr[lMaxIndex]){lMaxIndex = GetRightChild(aIndex);}if (lMaxIndex != aIndex){int lTemp = aArr[lMaxIndex];aArr[lMaxIndex] = aArr[aIndex];aArr[aIndex] = lTemp;MaxHeapfy(aArr,lMaxIndex,aHeapSize);}}void BuildMaxHeap(int* aArr, int aSize){for (int i = (aSize)/2-1; i >= 0; --i){MaxHeapfy(aArr,i,aSize);}}void HeapSort(int* aArr, int aSize){BuildMaxHeap(aArr,aSize);int lHeapSize = aSize;for (int i = (aSize)/2-1; i >= 0; --i){int lTemp = aArr[i];aArr[i] = aArr[0];aArr[0] = lTemp;--lHeapSize;MaxHeapfy(aArr,i,lHeapSize);}}int main(){int lArr[] = {1,-10,26,8,-90};int lSize = sizeof(lArr)/sizeof(int);HeapSort(lArr,lSize);for (int i = 0; i < lSize; ++i){cout << lArr[i] << endl;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.