How to implement the quicksort algorithm in Golang?

The quicksort algorithm in Golang can be implemented using the following steps:

  1. Choose a pivot element, which can be any element in the array. Typically, the first element is chosen as the pivot element.
  2. Divide the array into two parts, placing elements smaller than the pivot on the left and elements greater than the pivot on the right.
  3. Recursively perform quick sort on the left and right partitions.

Here is an example code implementation:

package main

import "fmt"

func quickSort(arr []int, low, high int) {
	if low < high {
		pivot := partition(arr, low, high)
		quickSort(arr, low, pivot-1)
		quickSort(arr, pivot+1, high)
	}
}

func partition(arr []int, low, high int) int {
	pivot := arr[low]
	for low < high {
		for low < high && arr[high] >= pivot {
			high--
		}
		arr[low] = arr[high]

		for low < high && arr[low] <= pivot {
			low++
		}
		arr[high] = arr[low]
	}
	arr[low] = pivot
	return low
}

func main() {
	arr := []int{9, 5, 7, 3, 1, 6, 0, 8, 4, 2}
	quickSort(arr, 0, len(arr)-1)
	fmt.Println(arr)
}

In the example code above, the quickSort function implements the quicksort algorithm, and the partition function is used to divide the array and return the final position of the pivot element. In the main function, we define an integer array to be sorted and call the quickSort function to sort it. Finally, we output the sorted result.

bannerAds