# 3.3.3 - Heap Sort

### 1. 演算法

將{5, 3, 2, 1, 7, 8, 9, 10}

1. 將資料以Bottom-Up方式建立Max-Heap
2. 執行Delete-Max
   1. SWAP(Root, the last node)
   2. 刪除最大值
   3. 將剩下的Heap調整為Max-Heap

![](/files/-LIU-TYCJUzIhttvPr60)

output=10

![](/files/-LIU-dpxD-HW-3ddO8HI)

output=9

![](/files/-LIU-iHkhA6_NeoIsmAf)

```
void HeapSort(char *heap){
    int n = strlen(heap);
    //build heap
    for (int i = n/2-1; i>=0; i--)  //i從最後一個父點開始
        AdjustBottomUp(heap, i, n-1);
    //delete max
    for (int i = n-1;i>0;i--){
        Swap(&heap[0], &heap[i]); //將max移到最後
        for (int j = i/2-1; j>=0; j--)
            AdjustBottomUp(heap, j, i-1);
    }
}
```

### 2. 性質

* Time Complexity: $$O(nlogn)$$&#x20;
  1. 以Bottom-Up建立Heap共花$$O(n)$$&#x20;
  2. 執行Delete-Max，每一回合共花 $$O(logn)$$，共有n回合
* Space Complexity: $$O(1)$$&#x20;

Heap sorting is a **unstable** sorting method.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://garychang.gitbook.io/data-structure/3-search/sophisticated-sorting/3.3.3-heap-sort.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
