Last active
October 16, 2017 03:32
-
-
Save franzwong/c92efe8573497707099417e719b4ccb5 to your computer and use it in GitHub Desktop.
Quick sort implemented in Golang
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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func Quicksort(elements []int, low int, high int) { | |
if (high > low) { | |
pivot := Partition(elements, low, high) | |
Quicksort(elements, low, pivot-1) | |
Quicksort(elements, pivot+1, high) | |
} | |
} | |
func Partition(elements []int, low int, high int) (int) { | |
fmt.Printf("partition: %d, %d\n", low, high) | |
pivot := high | |
i := low - 1 | |
for j := low; j < pivot; j++ { | |
if (elements[j] < elements[pivot]) { | |
i += 1 | |
elements[i], elements[j] = elements[j], elements[i] | |
} | |
} | |
elements[i+1], elements[pivot] = elements[pivot], elements[i+1] | |
fmt.Println(elements) | |
return i+1 | |
} | |
func GenerateElements(length int) ([]int) { | |
elements := []int{} | |
for i := 0; i < 10; i++ { | |
elements = append(elements, rand.Intn(100)) | |
} | |
return elements | |
} | |
func main() { | |
rand.Seed(time.Now().UTC().UnixNano()) | |
elements := GenerateElements(10) | |
fmt.Println(elements) | |
Quicksort(elements, 0, len(elements) - 1) | |
fmt.Println(elements) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment