Created
May 28, 2023 10:30
-
-
Save anadimisra/1dc626949f3345b7fbbcf938124c9266 to your computer and use it in GitHub Desktop.
Bubble Sort Exercise in GoLang
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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
numbers := []int{} | |
numbers = populateNumbers(strings.Fields(readUserInput()), numbers) | |
BubbleSort(numbers) | |
fmt.Println("Sorted numbers = ", numbers) | |
} | |
func readUserInput() string{ | |
fmt.Print("Enter numbers to be sorted separated by space (only upto 10 allowed) :") | |
in := bufio.NewReader(os.Stdin) | |
line, inerr := in.ReadString('\n') | |
if(inerr != nil){ | |
panic(inerr) | |
} | |
return line | |
} | |
func populateNumbers(inputs []string, numbers []int) []int{ | |
if(len(inputs)>10){ | |
log.Fatal("Only upto 10 inputs allowed") | |
} | |
for _, i := range inputs { | |
n, err := strconv.Atoi(i) | |
if err != nil { | |
panic(err) | |
} | |
numbers = append(numbers, n) | |
} | |
return numbers | |
} | |
func BubbleSort(numbers []int) { | |
for idx := 0; idx < len(numbers)-1; idx++ { | |
if(numbers[idx] > numbers[idx+1]){ | |
Swap(numbers, idx) | |
} | |
} | |
if(len(numbers)>=2){ | |
BubbleSort(numbers[:len(numbers)-1]) | |
} | |
} | |
func Swap(numbers []int, idx int) { | |
temp := numbers[idx] | |
numbers[idx] = numbers[idx+1] | |
numbers[idx+1] = temp | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment