diff --git a/algorithms/Go/README.md b/algorithms/Go/README.md index 0e12c10e..febe548e 100644 --- a/algorithms/Go/README.md +++ b/algorithms/Go/README.md @@ -19,7 +19,8 @@ ## Sorting - [Bubble Sort](sorting/bubble-sort.go) - [Insertion Sort](sorting/insertion-sort.go) -- [Quicksort](sorting/quicksort.go) +- [Quick Sort](sorting/quicksort.go) +- [Selection Sort](sorting/selection-sort.go) ## Recursion - [Fibonacci](recursion/fibonacci.go) diff --git a/algorithms/Go/sorting/selection-sort.go b/algorithms/Go/sorting/selection-sort.go new file mode 100644 index 00000000..4975ce34 --- /dev/null +++ b/algorithms/Go/sorting/selection-sort.go @@ -0,0 +1,62 @@ +/* + Selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. + The algorithm maintains two subarrays in a given array: + The subarray which is already sorted. + Remaining subarray which is unsorted. + Average Time Complexity: O(n^2) + + Link for reference: https://www.geeksforgeeks.org/selection-sort/ + +*/ + +package sorting + +import "fmt" + +func RunSelectionSortRec() { + arr := []int{7, 4, 7, 3, 2} + selSortRec(arr, len(arr)-1) //using recursion + fmt.Println(arr) // 2, 3, 4, 7, 7 +} +func RunSelectionSortIter() { + arr := []int{7, 4, 7, 3, 1} + selSort(arr) //using iteration + fmt.Println(arr) // 1, 3, 4, 7, 7 +} + +//sort using iterative method +func selSort(arr []int) { + for arrIndex := range arr { + minVal := arr[arrIndex] + minIndex := arrIndex + for subIndex := arrIndex + 1; subIndex < len(arr); subIndex++ { + if arr[subIndex] < minVal { + minVal = arr[subIndex] + minIndex = subIndex + } + } + arr[minIndex], arr[arrIndex] = arr[arrIndex], arr[minIndex] + } +} + +//sort using recursive method +func selSortRec(arr []int, i int) { + if i < 0 { + return + } + maxIn := maxSel(arr, i) + //i = len(arr)-1 + if i != maxIn { + arr[i], arr[maxIn] = arr[maxIn], arr[i] + } + selSortRec(arr, i-1) +} +func maxSel(arr []int, i int) int { + if i > 0 { + maxIn := maxSel(arr, i-1) + if arr[i] < arr[maxIn] { + return maxIn + } + } + return i +}