-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubbleSort.go
55 lines (51 loc) · 1.04 KB
/
bubbleSort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
//read input from user and parse string to int
func readInput() []int {
var stdin *bufio.Reader
stdin = bufio.NewReader(os.Stdin)
fmt.Println("Insert some numbers to be ordered: (ex. 3,1,2)")
s, _ := stdin.ReadString('\n')
s = s[0 : len(s)-1]
//testString := "2,5,13,59"
stringArray := strings.Split(s, ",")
//fmt.Printf("stringArray is %v\n", stringArray)
intArray := []int{}
for _, i := range stringArray {
j, err := strconv.Atoi(i)
if err != nil {
panic(err)
}
intArray = append(intArray, j)
}
return intArray
}
//sort array of integer passed as parameter
func bubbleSort(array []int) []int {
flag := true
n := len(array) - 2
for flag {
flag = false
for i := 0; i <= n; i++ {
if array[i] > array[i+1] {
temp := array[i]
array[i] = array[i+1]
array[i+1] = temp
flag = true
}
}
n = n - 1
}
return array
}
func main() {
intArray := readInput()
orderedArray := bubbleSort(intArray)
fmt.Printf("The ordered array is %v\n", orderedArray)
}