Skip to content

Commit abae230

Browse files
committed
add heap sort
1 parent 636fc7f commit abae230

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

src/main/kotlin/sort/HeapSort.kt

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package sort
2+
3+
import util.swap
4+
5+
/**
6+
* 完全二叉树
7+
* i 下标的左孩子 2i + 1
8+
* 右孩子 2i + 2
9+
* 父节点 (i-1)/2
10+
*/
11+
object HeapSort {
12+
fun sort(array: IntArray) {
13+
array.forEachIndexed { index, i ->
14+
heapInsert(index, array)
15+
}
16+
var heapSize = array.size
17+
while (heapSize > 0) {
18+
array.swap(0, --heapSize)
19+
heapify(heapSize, 0, array)
20+
}
21+
}
22+
23+
fun heapify(heapSize: Int, index: Int, array: IntArray) {
24+
var leftChildIndex = 2 * index + 1
25+
var tempIndex = index
26+
while (leftChildIndex < heapSize) {
27+
val maxChildIndex = if (leftChildIndex + 1 < heapSize) {
28+
if (array[leftChildIndex] >= array[leftChildIndex + 1]) leftChildIndex else leftChildIndex + 1
29+
} else {
30+
leftChildIndex
31+
}
32+
if (array[tempIndex] > array[maxChildIndex]) {
33+
return
34+
} else {
35+
array.swap(tempIndex, maxChildIndex)
36+
tempIndex = maxChildIndex
37+
leftChildIndex = 2 * tempIndex + 1
38+
}
39+
}
40+
}
41+
42+
private fun heapInsert(index: Int, array: IntArray) {
43+
var parentIndex = findParent(index)
44+
var insertIndex = index
45+
46+
while (array[parentIndex] < array[insertIndex]) {
47+
array.swap(parentIndex, insertIndex)
48+
insertIndex = parentIndex
49+
parentIndex = findParent(insertIndex)
50+
}
51+
}
52+
53+
private fun findParent(index: Int): Int {
54+
return (index - 1) / 2
55+
}
56+
}

src/main/kotlin/sort/QuickSort.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import util.swap
55

66
// 随机数下,数学期望 NLogN
77
// 无随机数情况,最差情况,单调序列 O(n*n) -> 由于划分值打得很偏
8+
// 空间复杂度 O(N) -> O(logN)
89
object QuickSort {
910
fun sort(array: IntArray) {
1011
rec(0, array.lastIndex, array)

src/main/kotlin/sort/TestSort.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,15 @@ class TestSort {
5959
Assert.assertTrue(array2.sameAs(array1))
6060
}
6161
}
62+
63+
@Test
64+
fun testHeap() {
65+
repeat(5) {
66+
val array1 = Logarithm.generateRandomArray(50, 50)
67+
val array2 = array1.clone()
68+
array2.sort()
69+
HeapSort.sort(array1)
70+
Assert.assertTrue(array2.sameAs(array1))
71+
}
72+
}
6273
}

0 commit comments

Comments
 (0)