Last active
December 23, 2017 14:56
-
-
Save treyhakanson/3856755ecb68eb82037e5c9d044090f8 to your computer and use it in GitHub Desktop.
Various sorting algorithms and implementations in the go programing languages.
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 ( | |
"fmt" | |
"math/rand" | |
) | |
// ============================================================================ | |
// bubble sort algorithm | |
func bubbleSort(arr []int) { | |
for i := 1; i < len(arr); i++ { | |
if arr[i] < arr[i - 1] { | |
tmp := arr[i - 1] | |
arr[i - 1] = arr[i] | |
arr[i] = tmp | |
i = 0 | |
} | |
} | |
} | |
// ============================================================================ | |
// ============================================================================ | |
// insertion sort algorithm | |
func insertionSort(arr []int) { | |
for i := 0; i < len(arr); i++ { | |
for j := 0; j < i; j++ { | |
if arr[j] > arr[i] { | |
tmp := arr[j] | |
arr[j] = arr[i] | |
arr[i] = tmp | |
} | |
} | |
} | |
} | |
// ============================================================================ | |
// ============================================================================ | |
// merges 2 sorted arrays into 1 array | |
func merge(pt1 []int, pt2 []int) []int { | |
totalLen := len(pt1) + len(pt2) | |
arr := []int{} | |
for i := 0; i < totalLen; i++ { | |
if pt1[0] < pt2[0] { | |
arr = append(arr, pt1[0]) | |
pt1 = pt1[1:] | |
} else { | |
arr = append(arr, pt2[0]) | |
pt2 = pt2[1:] | |
} | |
if len(pt1) == 0 || len(pt2) == 0 { | |
break | |
} | |
} | |
arr = append(arr, pt1...) | |
return append(arr, pt2...) | |
} | |
// merge sort algorithm | |
func mergeSort(arr []int) []int { | |
arrLen := len(arr) | |
if arrLen > 1 { | |
pt1 := mergeSort(arr[arrLen/2:]) | |
pt2 := mergeSort(arr[:arrLen/2]) | |
arr = merge(pt1, pt2) | |
} | |
return arr | |
} | |
// ============================================================================ | |
func main() { | |
sz := 50 | |
arr := make([]int, sz) | |
for i := 0; i < len(arr); i++ { | |
arr[i] = rand.Intn(sz) | |
} | |
fmt.Println("Initial Slice:", arr) | |
arr = mergeSort(arr) | |
fmt.Println("Sorted Slice: ", arr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment