编写一个用于堆排序(Heap Sort)的程序,并说明时间/空间复杂度。
Write a Heap Sort program and explain its time and space complexity.
题目类型: 技术面试题
这是一道技术面试题,常见于澳洲IT公司面试中。
难度: medium
分类: Coding
标签: heap sort, heap, complexity
参考答案摘要
答案 堆排序思路:先把数组建成最大堆,然后反复把堆顶(最大值)与末尾交换,并对剩余部分做下沉调整。建堆是 O(n),每次调整 O(log n),共 n 次,因此整体时间复杂度为 O(n log n) ,空间复杂度为 O(1) (原地排序)。 def heap_sort(a): n = len(a) def sift_down(i, size): while True: l = 2 * i + 1 ...
本题提供 STAR 原则详细解答和技术解析,登录匠人学院学习中心即可查看完整答案。