Last active
August 29, 2015 13:56
-
-
Save brnstz/8911156 to your computer and use it in GitHub Desktop.
Insertion sort in Go, using sort.Interface
This file contains hidden or 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
// https://github.com/brnstz/algo | |
package sorting | |
import ( | |
// Import the core sort package to use its interface, which declares | |
// Len(), Less(), and Swap() | |
"sort" | |
) | |
func InsertionSort(a sort.Interface) { | |
// Store the length of the incoming list to be sorted | |
aLen := a.Len() | |
// Declare two index variables | |
var i, j int | |
// Starting with second value, iterate outer loop over the | |
// remainder of the list | |
for i = 1; i < aLen; i++ { | |
// For every value of a[i] from the outer loop, start with index j=i, | |
// and go backwards in the list, swapping j with j-1 until you find | |
// a lower value in j-1. | |
for j = i; j > 0 && a.Less(j, j-1); j-- { | |
// Swap lower value back in the list | |
a.Swap(j, j-1) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment