Golang Quick Sort Algorithm

Quick sort is an algorithm for sorting the elements of a collection in an organized way. Parallelized quick sort is two to three times faster than merge sort and heap sort. The algorithm's performance is of the order O(n log n). This algorithm is a space-optimized version of the binary tree sort algorithm.

Golang Quick Sort Algorithm

Let's create a file named "quick_sort.go" and add the following source code to it:


package main

// importing fmt package
import (
	"fmt"
)

//Quick Sorter method
func QuickSorter(elements []int, below int, upper int) {
	if below < upper {
		var part int
		part = divideParts(elements, below, upper)
		QuickSorter(elements, below, part-1)
		QuickSorter(elements, part+1, upper)
	}
}

// divideParts method
func divideParts(elements []int, below int, upper int) int {
	var center int
	center = elements[upper]
	var i int
	i = below
	var j int
	for j = below; j < upper; j++ {
		if elements[j] <= center {
			swap(&elements[i], &elements[j])
			i += 1
		}
	}
	swap(&elements[i], &elements[upper])
	return i
}

//swap method
func swap(element1 *int, element2 *int) {
	var val int
	val = *element1
	*element1 = *element2
	*element2 = val
}

// main method
func main() {
	
	var elements []int
	elements = []int {11, 4, 18, 6, 19, 21, 71, 13, 15, 2}
	fmt.Print("Elements: ", elements, "\n")
	QuickSorter(elements, 0, len(elements) -1)
	fmt.Print("Sorted Elements: ", elements, "\n")
}

Run the following command to execute the quick_sort.go file:

G:\GoLang\examples>go run quick_sort.go
Elements: [11 4 18 6 19 21 71 13 15 2]
Sorted Elements: [2 4 6 11 13 15 18 19 21 71]