From ca16316d975f9678ecc45a8102e3c6226e7565ec Mon Sep 17 00:00:00 2001 From: nikochiko Date: Thu, 1 Oct 2020 10:31:24 +0530 Subject: [PATCH] Add exchange_selection_sort.go --- .../selection_sort/exchange_selection_sort.go | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Sorting/selection_sort/exchange_selection_sort.go diff --git a/Sorting/selection_sort/exchange_selection_sort.go b/Sorting/selection_sort/exchange_selection_sort.go new file mode 100644 index 0000000..e0cef7e --- /dev/null +++ b/Sorting/selection_sort/exchange_selection_sort.go @@ -0,0 +1,59 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +var reader *bufio.Reader = bufio.NewReader(os.Stdin) +var writer *bufio.Writer = bufio.NewWriter(os.Stdout) + +func selectionSort(n int, arr []int) { + // O(n^2) time + for j := 0; j < n; j++ { + swap_idx := j + for i := j + 1; i < n; i++ { + if arr[i] < arr[swap_idx] { + swap_idx = i + } + } + key := arr[j] + arr[j] = arr[swap_idx] + arr[swap_idx] = key + fmt.Printf("Step %d: %v\n", j+1, arr) + } +} + +func readArray(reader *bufio.Reader, n int) []int { + str, _, err := reader.ReadLine() + if err != nil { + panic(err) + } + + temp := strings.Split(string(str), " ") + arr := make([]int, n) + + for i := 0; i < n; i++ { + arr[i], err = strconv.Atoi(temp[i]) + if err != nil { + panic(err) + } + } + + return arr +} + +func main() { + defer writer.Flush() + + var n int + fmt.Fscanf(reader, "%d\n", &n) + arr := readArray(reader, n) + + fmt.Println("Before:", arr) + selectionSort(n, arr) + fmt.Println("After:", arr) +}