-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Hoanh An
committed
Sep 13, 2019
1 parent
0733bbe
commit 49ce362
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |