From 92680f9485e5d7eada5687a0246ae260989b2019 Mon Sep 17 00:00:00 2001 From: Hoanh An Date: Sat, 21 Sep 2019 15:36:01 -0400 Subject: [PATCH] tmp heapsort --- other/heapsort_test.go | 58 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 other/heapsort_test.go diff --git a/other/heapsort_test.go b/other/heapsort_test.go new file mode 100644 index 0000000..4a330bb --- /dev/null +++ b/other/heapsort_test.go @@ -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 + } +}