Skip to content

Instantly share code, notes, and snippets.

@samacs
Created May 21, 2019 00:39
Show Gist options
  • Save samacs/c992e548bec369f4cca54de3bdd4fe07 to your computer and use it in GitHub Desktop.
Save samacs/c992e548bec369f4cca54de3bdd4fe07 to your computer and use it in GitHub Desktop.
Sort solution
package main
import "fmt"
// Language: Go
//
// Running:
//
// Assuming `elements := []int{1, 2, 3, 4}`
//
// ```go
// $ go run main.go
// Unsorted: [1 2 3 4]
// Sorted: [2 1 4 3]
// ```
func main() {
elements := []int{1, 2, 3, 4}
fmt.Printf("Unsorted: %+v\n", elements)
length := len(elements)
for i := 0; i < length; i += 2 {
if i > 0 && elements[i-1] > elements[i] {
elements[i-1], elements[i] = elements[i], elements[i-1]
}
if i < length-1 && elements[i] < elements[i+1] {
elements[i], elements[i+1] = elements[i+1], elements[i]
}
}
fmt.Printf("Sorted: %+v\n", elements)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment