@@ -6,37 +6,44 @@ import (
66 "github.com/deeper-x/data_struct_algs/constraints"
77)
88
9- // quicksort.go
10- // description: Implementation of in-place quicksort algorithm
11- // details:
12- // A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)
13- // worst time complexity: O(n^2)
14- // average time complexity: O(n log n)
15- // space complexity: O(log n)
16- // see sort_test.go for a test implementation, test function TestQuickSort.
17-
9+ // / Quicksort sorts an array using the quicksort algorithm.
10+ // / It selects a pivot, partitions the array, and recursively sorts the subarrays.
11+ // /
12+ // / Parameters:
13+ // / - arr []T: A slice of ordered elements to be sorted.
14+ // /
15+ // / Returns:
16+ // / - []T: The sorted slice.
1817func Quicksort [T constraints.Ordered ](arr []T ) []T {
18+ /// Base case: If the array has 0 or 1 element, it's already sorted.
1919 if len (arr ) < 2 {
2020 return arr
2121 }
2222
23+ /// Initialize pointers for partitioning
2324 left , right := 0 , len (arr )- 1
2425
26+ /// Select a random pivot index
2527 pivot := rand .Int () % len (arr )
2628
29+ /// Move pivot element to the end of the array
2730 arr [pivot ], arr [right ] = arr [right ], arr [pivot ]
2831
32+ /// Partitioning: Move elements smaller than pivot to the left side
2933 for i := range arr {
30- if arr [i ] < arr [right ] {
31- arr [left ], arr [i ] = arr [i ], arr [left ]
34+ if arr [i ] < arr [right ] { /// Compare with pivot element
35+ arr [left ], arr [i ] = arr [i ], arr [left ] /// Swap smaller element to the left
3236 left ++
3337 }
3438 }
3539
40+ /// Place the pivot element in its correct position
3641 arr [left ], arr [right ] = arr [right ], arr [left ]
3742
38- Quicksort (arr [:left ])
39- Quicksort (arr [left + 1 :])
43+ /// Recursively apply Quicksort to the left and right subarrays
44+ Quicksort (arr [:left ]) /// Sort elements before pivot
45+ Quicksort (arr [left + 1 :]) /// Sort elements after pivot
4046
47+ /// Return the sorted array
4148 return arr
4249}
0 commit comments