Skip to content

Commit

Permalink
tmp heapsort
Browse files Browse the repository at this point in the history
  • Loading branch information
Hoanh An committed Sep 21, 2019
1 parent deee80e commit 92680f9
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions other/heapsort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Problem:
// Implement heapsort.
//
// Mechanic:
// Similar to selection sort, repeatedly choose the largest item and move it to
// the end of the array using a heap.
//
// Cost:
// O(nlogn) time and O(1) space.

package other

import (
"testing"

"github.com/hoanhan101/algo/common"
)

func TestHeapsort(t *testing.T) {
tests := []struct {
in []int
expected []int
}{
{[]int{}, []int{}},
{[]int{1}, []int{1}},
{[]int{1, 2}, []int{1, 2}},
{[]int{2, 1}, []int{1, 2}},
{[]int{2, 1, 3}, []int{1, 2, 3}},
{[]int{1, 1, 1}, []int{1, 1, 1}},
{[]int{2, 1, 2}, []int{1, 2, 2}},
{[]int{1, 2, 4, 3, 6, 5}, []int{1, 2, 3, 4, 5, 6}},
{[]int{6, 2, 4, 3, 1, 5}, []int{1, 2, 3, 4, 5, 6}},
{[]int{6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6}},
}

for _, tt := range tests {
heapsort(tt.in)
common.Equal(t, tt.expected, tt.in)
}
}

func heapsort(in []int) {
minIndex := 0
for i := 0; i < len(in)-1; i++ {
minIndex = i
// find the minimum in the rest of the array.
for j := i + 1; j < len(in); j++ {
if in[j] < in[minIndex] {
minIndex = j
}
}

// swap the minimum value with the first value.
tmp := in[i]
in[i] = in[minIndex]
in[minIndex] = tmp
}
}

0 comments on commit 92680f9

Please sign in to comment.