目錄
堆排序(回顧)
基本思路
代碼實現
向下調整排序?AdjustDown
?建堆+排序
時間復雜度
特性總結
堆排序(回顧)
重點回顧戳👉堆排序
基本思路
堆排序(Heapsort)是指利用堆積樹(堆)這種數據結構所設計的一種排序算法,它是選擇排序的一種。它是通過堆來進行選擇數據。需要注意的是排升序要建大堆,排降序建小堆。
這里舉例建升序,也就是大堆。
①先將數組中的元素向下調整建堆
②循環以下操作:
- 交換頭尾
- 向下調整(最后一個元素不參與調整)
?
代碼實現
向下調整排序?AdjustDown
void Swap(HPDataType* p1, HPDataType* p2)
{HPDataType tmp = *p1;*p1 = *p2;*p2 = tmp;
}void AdjustDown(int* a, int size, int parent)
{int child = parent * 2 + 1;while (child < size){//建大堆,升序if (child + 1 < size && a[child + 1] > a[child]){++child;}if (a[child] > a[parent]){Swap(&a[child], &a[parent]);parent = child;child = parent * 2 + 1;}else{break;}}}
?建堆+排序
void HeapSort(int* a, int n)
{//向下調整建堆for (int i = (n-1-1)/2; i >= 0; --i){AdjustDown(a, n, i);}int end = n - 1;while (end > 0){Swap(&a[0], &a[end]);AdjustDown(a, end, 0);--end;}
}int main()
{int a[10] = { 4, 6, 2, 1, 5, 8, 2, 9 };int size = sizeof(a) / sizeof(a[0]);HeapSort(a, size);for (int i = 0; i < size; i++){printf("%d ", a[i]);}return 0;
}
時間復雜度
O(N*logN)
特性總結
1. 堆排序使用堆來選數,效率就高了很多。
2. 時間復雜度:O(N*logN)
3. 空間復雜度:O(1)
4. 穩定性:不穩定