Skip to content

Instantly share code, notes, and snippets.

@nbari
Last active August 29, 2015 14:20
Show Gist options
  • Save nbari/9f4666ad51565a03e260 to your computer and use it in GitHub Desktop.
Save nbari/9f4666ad51565a03e260 to your computer and use it in GitHub Desktop.
insert sort + unique
//Create some data for testing using:
// jot -s, -r 10000000 1 256 > data
//Test using:
// cat data | ./sort
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
)
func main() {
start := time.Now()
out := []int{}
set := map[int]struct{}{}
//value := "1,9,5,5,b,4,3,3,a"
reader := bufio.NewReader(os.Stdin)
value, _ := reader.ReadString('\n')
// convert to int and add to a set to remove dupes
for _, n := range strings.Split(value, ",") {
num, err := strconv.Atoi(n)
if err != nil {
continue
}
if _, ok := set[num]; ok {
continue
}
out = append(out, num)
set[num] = struct{}{}
// insertion sort
for x := 1; x < len(out); x++ {
value := out[x]
y := x - 1
for y >= 0 && out[y] > value {
out[y+1] = out[y]
y = y - 1
}
out[y+1] = value
}
}
elapsed := time.Since(start)
fmt.Println(out, elapsed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment