Application
Create new folder named src. In src folder, create new file named main.go as below:
package main
import (
"fmt"
"strings"
)
func main() {
var names = [5]string{"mary", "peter", "kevin", "anna", "johny"}
result1 := SortASC(names)
fmt.Println("Sort ASC")
fmt.Println(result1)
result2 := SortDESC(names)
fmt.Println("Sort DESC")
fmt.Println(result2)
}
func SortASC(a [5]string) [5]string {
for i := 0; i < len(a)-1; i++ {
for j := i + 1; j < len(a); j++ {
if strings.Compare(a[i], a[j]) > 0 {
temp := a[i]
a[i] = a[j]
a[j] = temp
}
}
}
return a
}
func SortDESC(a [5]string) [5]string {
for i := 0; i < len(a)-1; i++ {
for j := i + 1; j < len(a); j++ {
if strings.Compare(a[i], a[j]) < 0 {
temp := a[i]
a[i] = a[j]
a[j] = temp
}
}
}
return a
}
Output
Open Terminal windows in Visual Studio Code and run command line: go run main.go
Sort ASC
[anna johny kevin mary peter]
Sort DESC
[peter mary kevin johny anna]