Created
December 4, 2018 22:20
-
-
Save raninho/36056dddae6f603dd4278acef133a4f7 to your computer and use it in GitHub Desktop.
BubbleSort example
This file contains hidden or 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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strconv" | |
"strings" | |
) | |
type name struct { | |
fname string | |
lname string | |
} | |
func Swap(values []int, pos int) { | |
temp := values[pos] | |
values[pos] = values[pos+1] | |
values[pos+1] = temp | |
} | |
func BubbleSort(values []int) { | |
for n := len(values); n > 1; n-- { | |
for i := 0; i < n-1; i++ { | |
if values[i] > values[i+1] { | |
Swap(values, i) | |
} | |
} | |
} | |
} | |
func main() { | |
values := make([]int, 0, 10) | |
scanner := bufio.NewScanner(os.Stdin) | |
//scanner.Split(bufio.ScanWords) | |
fmt.Printf("Please enter integer numbers: ") | |
scanner.Scan() | |
valstring := scanner.Text() | |
for _, sval := range strings.Split(valstring, " ") { | |
val, err := strconv.Atoi(sval) | |
if err == nil { | |
values = append(values, val) | |
} else { | |
fmt.Printf("Error parsing the integer %s\n", sval) | |
} | |
} | |
BubbleSort(values) | |
fmt.Printf("sorted: %v\n", values) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment