堆排序(C#)
(二叉)堆數據結構是一種數組對象,它可以被視爲一顆完全二叉樹.
完全二叉樹(Complete Binary Tree)
若設二叉樹的高度爲h,除第 h 層外,其它各層 (1~h-1) 的結點數都達到最大個數,第 h 層所有的節點都連續集中在最左邊,這就是完全二叉樹。
完全二叉樹是由滿二叉樹而引出來的。對於深度爲K的,有N個結點的二叉樹,
當且僅當其每一個結點都與深度爲K的滿二叉樹中編號從1至n的結點一一對應時稱之爲完全二叉樹。
(完全二叉樹)
在堆中對於某一節點i,如果它有左右兒子,則左兒子Left(i)的索引(從0開始)爲i*2+1,
右兒子Right(i)的索引爲i*2+2,節點i的父節點索引爲(i-1)/2.
代碼如下:
-
-
-
- public static int[] MinHeapSort(int[] a)
- {
-
- BulidMinHeap(a);
-
- int aLenght = a.Length;
- int heapSize = aLenght;
- int[] sorttedArray = new int[a.Length];
- for (int i = 0; i < aLenght; i++)
- {
-
- sorttedArray[i] = a[0];
- a[0] = a[heapSize - 1];
-
- MinHeapify(a, 0, heapSize--);
- }
-
- return sorttedArray;
- }
-
-
-
-
- public static void BulidMinHeap(int[] a)
- {
- for (int i = a.Length / 2 - 1; i >= 0; i--)
- {
- MinHeapify(a, i, a.Length);
- }
- }
-
-
-
-
- public static void MinHeapify(int[] a, int i, int heapSize)
- {
- int left = i * 2 + 1;
- int right = i * 2 + 2;
- int mivValueIndex = i;
-
- if (left < heapSize && a[i] > a[left])
- {
-
- mivValueIndex = left;
- }
- if (right < heapSize && a[mivValueIndex] > a[right])
- {
-
- mivValueIndex = right;
- }
-
- if (mivValueIndex != i)
- {
-
- int temp = a[i];
- a[i] = a[mivValueIndex];
- a[mivValueIndex] = temp;
-
-
- MinHeapify(a, mivValueIndex, heapSize);
- }
- }