Last active
May 26, 2016 16:44
-
-
Save scbizu/c836bf1edc22e70683997484c19401c9 to your computer and use it in GitHub Desktop.
Go Basic Sort
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" | |
"time" | |
) | |
//bubbleSort | |
func bubbleSort(origin []int) []int { | |
count := len(origin) - 1 | |
for i := 0; i < count; i++ { | |
for j := 0; j < count-i; j++ { | |
if origin[j] < origin[j+1] { | |
//bubbleSort switch origin[j+1] adn origin[j] and let the smallest/largest one fall into the bottom | |
t := origin[j] | |
origin[j] = origin[j+1] | |
origin[j+1] = t | |
} | |
} | |
} | |
return origin | |
} | |
//selectionSort put the ele in right place(MAX OR MIN) | |
func selectionSort(origin []int) []int { | |
count := len(origin) | |
for i := 0; i < count-1; i++ { | |
min := i | |
for j := i + 1; j < count; j++ { | |
if origin[j] < origin[min] { | |
min = j | |
} | |
} | |
t := origin[min] | |
origin[min] = origin[i] | |
origin[i] = t | |
} | |
return origin | |
} | |
//Insertion Sort Insert the num to right palce (Traverse: from the behind to the front) | |
func insertionSort(origin []int) []int { | |
count := len(origin) | |
for i := 1; i < count; i++ { | |
t := origin[i] | |
for j := i - 1; j >= 0 && origin[j] > t; j-- { | |
origin[j+1] = origin[j] | |
origin[j] = t | |
} | |
} | |
return origin | |
} | |
//Shell Sort accroding to the steps | |
func shellSort(origin []int) []int { | |
count := len(origin) | |
for step := count >> 1; step > 0; step >>= 1 { | |
for i := step; i < count; i++ { | |
t := origin[i] | |
for j := i - step; j > 0 && origin[j] > t; j -= step { | |
origin[j+step] = origin[j] | |
origin[j] = t | |
} | |
} | |
} | |
return origin | |
} | |
//TODO:quickSort | |
func main() { | |
switchSortTime := time.Now() | |
origin := []int{95, 45, 15, 78, 84, 51, 24, 12} | |
res := bubbleSort(origin) | |
fmt.Println("Runtime:", time.Since(switchSortTime)) | |
fmt.Println("Result:", res) | |
selectionSortTime := time.Now() | |
origin2 := []int{95, 45, 15, 78, 84, 51, 24, 12} | |
res2 := selectionSort(origin2) | |
fmt.Println("Runtime:", time.Since(selectionSortTime)) | |
fmt.Println("Result:", res2) | |
insertionSortTime := time.Now() | |
origin3 := []int{95, 45, 15, 78, 84, 51, 24, 12} | |
res3 := insertionSort(origin3) | |
fmt.Println("Runtime:", time.Since(insertionSortTime)) | |
fmt.Println("Result:", res3) | |
shellSortTime := time.Now() | |
origin4 := []int{95, 45, 15, 78, 84, 51, 24, 12} | |
res4 := insertionSort(origin4) | |
fmt.Println("Runtime:", time.Since(shellSortTime)) | |
fmt.Println("Result:", res4) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment