Skip to content

Instantly share code, notes, and snippets.

@rahulkushwaha12
Created January 21, 2020 04:33
Show Gist options
  • Save rahulkushwaha12/9814d99d045184df94a4476cde616387 to your computer and use it in GitHub Desktop.
Save rahulkushwaha12/9814d99d045184df94a4476cde616387 to your computer and use it in GitHub Desktop.
Selection sort in go
package main
import (
"fmt"
)
/*
5
25, 17, 31, 13, 2
sorted array [2 13 17 25 31]
Worst Case Time Complexity [ Big-O ]: O(n2)
Best Case Time Complexity [Big-omega]: O(n2)
Average Time Complexity [Big-theta]: O(n2)
*/
func main() {
var n int
fmt.Println("enter the no of inputs")
fmt.Scanln(&n)
arr := make([]int, n)
fmt.Println("enter the numbers >")
for i := 0; i < n; i++ {
fmt.Scan(&arr[i])
}
selectionSort(&arr, 0, n-1)
fmt.Println("sorted array ", arr)
}
func selectionSort(a *[]int, s, e int) {
arr := *a
for i := s; i <= e; i++ {
index := minIndex(a, i, e)
if i != index {
t := arr[i]
arr[i] = arr[index]
arr[index] = t
}
}
}
func minIndex(a *[]int, s, e int) int {
arr := *a
minIndex := s
for i := s + 1; i <= e; i++ {
if arr[i] < arr[minIndex] {
minIndex = i
}
}
return minIndex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment