You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6 KiB
Go

// A maximum of 3 points will be given for the first test execution, if the program correctly prints the sorted slice
// after entering three distinct integers. **Points are awarded incrementally each time that an integer
// is added and it correctly prints the sorted slice.
//A maximum of 2 points will be given for the second test execution,
// if the program correctly prints the sorted slice after entering four distinct integers.
// **Points are awarded if it correctly prints the sorted slice after adding the fourth integer.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func stringsToIntegers(inputStrings []string) []int {
integers := make([]int, len(inputStrings))
for i, v := range inputStrings {
intValue, err := strconv.Atoi(v)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s could not be converted to integer", v)
os.Exit(1)
}
integers[i] = intValue
}
return integers
}
func sortIntegers(integers []int) {
// Insertion sort O(n^2)
i := 1
for i < len(integers) {
insert := integers[i]
j := i - 1
for j >= 0 {
if insert < integers[j] {
integers[j+1] = integers[j]
j -= 1
} else {
break
}
}
integers[j+1] = insert
i += 1
}
}
func main() {
inputReader := bufio.NewReader(os.Stdin)
var integers []int
for {
fmt.Println("Enter a integer of text: ")
line, _ := inputReader.ReadString('\n')
}
fmt.Println("Enter a line of text: ")
line, _ := inputReader.ReadString('\n')
integersList := stringsToIntegers(strings.Split(line[:len(line)-1], " "))
fmt.Println("You entered:", integersList)
sortIntegers(integersList)
fmt.Println("Those sorted are:", integersList)
}