Last active
April 28, 2025 14:28
-
-
Save rphuber/8c9f76b536e19864f35e4f912d230e6b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package main | |
import ( | |
"slices" | |
) | |
func main() { | |
} | |
func find_smallest(arr []int) int { | |
smallest_index := 0 | |
for idx, value := range arr { | |
if value < arr[smallest_index] { | |
smallest_index = idx | |
} | |
} | |
return smallest_index | |
} | |
func selection_sort(arr []int) []int { | |
sorted_arr := []int{} | |
for len(arr) > 0 { | |
smallest_index := find_smallest(arr) | |
sorted_arr = append(sorted_arr, arr[smallest_index]) | |
arr = slices.Delete(arr, smallest_index, smallest_index+1) | |
} | |
return sorted_arr | |
} |
This file contains hidden or 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
package main | |
import ( | |
"reflect" | |
"testing" | |
) | |
func TestFindSmallest(t *testing.T) { | |
tests := []struct { | |
name string | |
input []int | |
expected int | |
}{ | |
{"Empty array", []int{}, 0}, | |
{"Single element", []int{1}, 0}, | |
{"Smallest at beginning", []int{1, 2, 3, 4}, 0}, | |
{"Smallest in middle", []int{4, 3, 1, 5}, 2}, | |
{"Smallest at end", []int{5, 4, 3, 1}, 3}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
if got := find_smallest(tt.input); got != tt.expected { | |
t.Errorf("find_smallest() = %v, want %v", got, tt.expected) | |
} | |
}) | |
} | |
} | |
func TestSelectionSort(t *testing.T) { | |
tests := []struct { | |
name string | |
input []int | |
expected []int | |
}{ | |
{"Empty array", []int{}, []int{}}, | |
{"Single element", []int{1}, []int{1}}, | |
{"Already sorted", []int{1, 2, 3, 4}, []int{1, 2, 3, 4}}, | |
{"Reverse sorted", []int{4, 3, 2, 1}, []int{1, 2, 3, 4}}, | |
{"Random order", []int{3, 1, 4, 2}, []int{1, 2, 3, 4}}, | |
{"Duplicate elements", []int{3, 1, 3, 2}, []int{1, 2, 3, 3}}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
// Create a copy of input to avoid modifying the original | |
input := make([]int, len(tt.input)) | |
copy(input, tt.input) | |
if got := selection_sort(input); !reflect.DeepEqual(got, tt.expected) { | |
t.Errorf("selection_sort() = %v, want %v", got, tt.expected) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment