Skip to content

Commit

Permalink
selection sort
Browse files Browse the repository at this point in the history
  • Loading branch information
Hoanh An committed Sep 13, 2019
1 parent 0733bbe commit 49ce362
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions other/selection_sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Implement selection sort.

package other

import (
"testing"

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

func TestSelectionSort(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 {
selectionSort(tt.in)
common.Equal(t, tt.expected, tt.in)
}
}

func selectionSort(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 49ce362

Please sign in to comment.