1. 程式人生 > >不穩定的排序

不穩定的排序

#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;


void HeapAdjust(int* pHeap, int i, int length)
{
    int child;
    for (; 2*i + 1 < length; i = child)
    {
		child = i*2 + 1;
        int rightChild = child + 1;
        if (rightChild < length && pHeap[rightChild]>pHeap[child]) child = rightChild;
        if (pHeap[child] > pHeap[i])
        {
            int temp;
            temp = pHeap[child];
            pHeap[child] = pHeap[i];
            pHeap[i] = temp;
        }
        else
        {
           break;
        }
    }
}


void HeapSort(int* pHeap, int length)
{
    for (int i = length/2 - 1; i >= 0; i--)
    {
        HeapAdjust(pHeap, i, length);
    }

   for (int i = length - 1; i > 0; i--)
   {
        int temp;
        temp = pHeap[0];
        pHeap[0] = pHeap[i];
        pHeap[i] = temp;
        HeapAdjust(pHeap, 0, i);
   }
}

int main()
{
   int nArray[10];
   copy(istream_iterator<int>(std::cin), istream_iterator<int>(), nArray);
   HeapSort(nArray, 10);
   copy(nArray, nArray + 10, ostream_iterator<int>(std::cout, " "));
   system("pause");
}<span style="white-space:pre">	</span>
注意:1.這裡陣列的索引是零開頭的,所以最後一個非葉子節點是length/2 - 1
      2.陣列的索引是零開頭的,節點i的左子樹是2*i+1,右子樹是2*i+2