-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.go
More file actions
48 lines (38 loc) · 1.09 KB
/
quick_sort.go
File metadata and controls
48 lines (38 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"math/rand"
)
// QuickSort sorts the array using the quicksort algorithm
func QuickSort(arr []int, low, high int, metrics *Metrics) {
if low < high {
pi := randomizedPartition(arr, low, high, metrics)
// Recursively sort elements before and after partition
QuickSort(arr, low, pi-1, metrics)
QuickSort(arr, pi+1, high, metrics)
}
}
// randomizedPartition selects a random pivot and partitions the array
func randomizedPartition(arr []int, low, high int, metrics *Metrics) int {
// Select a random pivot index
pivotIndex := rand.Intn(high-low+1) + low
arr[pivotIndex], arr[high] = arr[high], arr[pivotIndex]
metrics.Swaps++
return partition(arr, low, high, metrics)
}
// partition partitions the array around a pivot
func partition(arr []int, low, high int, metrics *Metrics) int {
pivot := arr[high]
i := low - 1
for j := low; j < high; j++ {
metrics.Comparison++
if arr[j] <= pivot {
i++
// Swap arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
metrics.Swaps++
}
}
arr[i+1], arr[high] = arr[high], arr[i+1]
metrics.Swaps++
return i + 1
}