Last active
June 3, 2017 22:50
-
-
Save gerep/1068ddf944011ecf5530e095f6ecb80c to your computer and use it in GitHub Desktop.
Insertion Sort - Part 1 - https://www.hackerrank.com/challenges/insertionsort1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
s := bufio.NewScanner(os.Stdin) | |
var l [2]string | |
var c int | |
for s.Scan() { | |
l[c] = s.Text() | |
c++ | |
} | |
if err := s.Err(); err != nil { | |
log.Fatal(err) | |
} | |
size, err := strconv.Atoi(l[0]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
t := strings.Split(l[1], " ") | |
var n []int | |
for _, v := range t { | |
i, err := strconv.Atoi(v) | |
if err != nil { | |
log.Fatal(err) | |
} | |
n = append(n, i) | |
} | |
for i := 1; i <= size-1; i++ { | |
x := n[i] | |
j := i | |
for j > 0 && n[j-1] > x { | |
n[j] = n[j-1] | |
j = j - 1 | |
fmt.Printf("%s\n", arrayToString(n)) | |
} | |
n[j] = x | |
} | |
fmt.Printf("%s\n", arrayToString(n)) | |
} | |
func arrayToString(l []int) (s string) { | |
for _, v := range l { | |
s = s + strconv.Itoa(v) + " " | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment