File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package sort
2+
3+ import "github.com/deeper-x/data_struct_algs/constraints"
4+
5+ // / Partition rearranges the elements of arr[low:high] around a pivot.
6+ // / It ensures that elements less than or equal to the pivot are on the left,
7+ // / and elements greater than the pivot are on the right. The pivot is chosen
8+ // / as the last element in the range.
9+ // /
10+ // / Parameters:
11+ // / - arr []T: A slice of ordered elements.
12+ // / - low, high int: The indices defining the subarray to partition.
13+ // /
14+ // / Returns:
15+ // / - int: The final index of the pivot after partitioning.
16+ func Partition [T constraints.Ordered ](arr []T , low , high int ) int {
17+ /// Index to track the correct position for smaller elements
18+ index := low - 1
19+
20+ /// Choosing the pivot as the last element
21+ pivotElement := arr [high ]
22+
23+ /// Iterate through the array, moving smaller elements to the left
24+ for i := low ; i < high ; i ++ {
25+ if arr [i ] <= pivotElement {
26+ index += 1
27+ arr [index ], arr [i ] = arr [i ], arr [index ] /// Swap to move smaller element
28+ }
29+ }
30+
31+ /// Swap pivot into its correct position
32+ arr [index + 1 ], arr [high ] = arr [high ], arr [index + 1 ]
33+
34+ /// Return the final pivot index
35+ return index + 1
36+ }
Original file line number Diff line number Diff line change 1+ package sort
2+
3+ import (
4+ "math/rand"
5+
6+ "github.com/deeper-x/data_struct_algs/constraints"
7+ )
8+
19// quicksort.go
210// description: Implementation of in-place quicksort algorithm
311// details:
715// space complexity: O(log n)
816// see sort_test.go for a test implementation, test function TestQuickSort.
917
10- package sort
11-
12- import (
13- "math/rand"
14-
15- "github.com/deeper-x/data_struct_algs/constraints"
16- )
17-
1818func Quicksort [T constraints.Ordered ](arr []T ) []T {
1919 if len (arr ) < 2 {
2020 return arr
You can’t perform that action at this time.
0 commit comments