This repository has been archived by the owner on Feb 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4 from nikochiko/SelectionSortGo
Add Go implementation for selection sort
- Loading branch information
Showing
1 changed file
with
59 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,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) | ||
} |