From b36b6c759e9269b1e7eda2fbfe1af8be3b3eeb77 Mon Sep 17 00:00:00 2001 From: Ivan Li Date: Sat, 12 Jan 2019 20:45:41 +0800 Subject: [PATCH] fix heap sort algo --- scala/src/main/scala/ch28_heap/Heap.scala | 4 ++-- scala/src/test/scala/ch28_heap/HeapTest.scala | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/scala/src/main/scala/ch28_heap/Heap.scala b/scala/src/main/scala/ch28_heap/Heap.scala index 6bbbd6e..f5f43b6 100644 --- a/scala/src/main/scala/ch28_heap/Heap.scala +++ b/scala/src/main/scala/ch28_heap/Heap.scala @@ -47,9 +47,9 @@ class Heap(val capacity: Int, var elementCount: Int = 0) { def removeMax(): Int = { require(elementCount > 0, "heap is empty") val result = array(1) - elementCount -= 1 array(1) = array(elementCount) - heapifyTopDown(1, elementCount - 1) + elementCount -= 1 + heapifyTopDown(1, elementCount) result } diff --git a/scala/src/test/scala/ch28_heap/HeapTest.scala b/scala/src/test/scala/ch28_heap/HeapTest.scala index 6cecc53..3e9051c 100644 --- a/scala/src/test/scala/ch28_heap/HeapTest.scala +++ b/scala/src/test/scala/ch28_heap/HeapTest.scala @@ -31,11 +31,11 @@ class HeapTest extends FlatSpec with Matchers { heap.removeMax() should equal(27) } -// it should "sort array" in { -// val nums = Array(33, 27, 21, 16, 13, 15, 19, 5, 6, 7, 8, 1, 2, 12) -// val result = Heap.heapSort(nums) -// -// result.mkString("") should equal(nums.sorted.mkString("")) -// } + it should "sort array" in { + val nums = Array(33, 27, 21, 16, 13, 15, 19, 5, 6, 7, 8, 1, 2, 12) + val result = Heap.heapSort(nums) + + result.mkString("") should equal(nums.sorted.mkString("")) + } }