Skip to content

Commit b3504c4

Browse files
committed
partition refactored
1 parent b2e0775 commit b3504c4

2 files changed

Lines changed: 44 additions & 8 deletions

File tree

sort/partition.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

sort/quicksort.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
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:
@@ -7,14 +15,6 @@
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-
1818
func Quicksort[T constraints.Ordered](arr []T) []T {
1919
if len(arr) < 2 {
2020
return arr

0 commit comments

Comments
 (0)