Skip to content

Instantly share code, notes, and snippets.

@esimov
Last active August 29, 2015 13:58
Show Gist options
  • Save esimov/10021745 to your computer and use it in GitHub Desktop.
Save esimov/10021745 to your computer and use it in GitHub Desktop.
Sorting inverted maps in Go lang using Bubblesort sorting algorithm
package main
import (
"fmt"
)
var (
values = map[string]int{
"alpha": 34, "bravo": 56, "charlie": 23,
"delta": 87, "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16,
"indio": 87, "juliet": 65, "kilo": 43, "lima": 98}
)
func main() {
//Inverting maps
invMap := make(map[int]string, len(values))
for k,v := range values {
invMap[v] = k
}
//Sorting
sortedKeys := make([]int, len(invMap))
var i int = 0
for k := range invMap {
sortedKeys[i] = k
i++
}
fmt.Println("Sorted keys")
bubbleSorted := BubbleSort(sortedKeys)
fmt.Println(bubbleSorted)
fmt.Println("Inverted map...")
for _,k := range bubbleSorted {
fmt.Printf("Key: %v, Value : %v\n", k, invMap[k])
}
}
//Bubblesort
func BubbleSort(arr[] int)[]int {
for i:=1; i< len(arr); i++ {
for j:=0; j < len(arr)-i; j++ {
if (arr[j] > arr[j+1]) {
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment