Algorithms and Data Structures - Quick Sort

Understand Quick Sort: O(n log n) average, O(n²) worst-case time complexity. Covers pivot selection, partitioning into low/high ranges, and a randomized Go implementation.

Read in: ja
Algorithms and Data Structures - Quick Sort

Overview

Referencing Algorithm Encyclopedia, we learn about algorithms and data structures.

The implementation is also available on github - bmf-san/road-to-algorithm-master.

Quick Sort

Computational Time

Implementation

package main

import (
	"fmt"
	"math/rand"
)

func quickSort(n []int) []int {
	if len(n) <= 1 {
		return n
	}

	pivot := n[rand.Intn(len(n))]

	low := make([]int, 0, len(n))
	high := make([]int, 0, len(n))
	middle := make([]int, 0, len(n))

	for _, i := range n {
		switch {
		case i < pivot:
			low = append(low, i)
		case i == pivot:
			middle = append(middle, i)
		case i > pivot:
			high = append(high, i)
		}
	}

	low = quickSort(low)
	high = quickSort(high)

	low = append(low, middle...)
	low = append(low, high...)

	return low
}

func main() {
	n := []int{2, 5, 7, 1, 3, 9}
	fmt.Println(quickSort(n))
}

References

Tags: Quick Sort
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles