File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ // description: Implementation of in-place quicksort algorithm
2
+ // details:
3
+ // A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)
4
+ // author(s) [Taj](https://github.com/tjgurwara99)
5
+
6
+ fn Partition[T: ordered](mut arr: []T, low: int, high: int): int {
7
+ mut index := low - 1
8
+ pivotElement := arr[high]
9
+ mut i := low
10
+ for i < high; i++ {
11
+ if arr[i] <= pivotElement {
12
+ index += 1
13
+ arr[index], arr[i] = arr[i], arr[index]
14
+ }
15
+ }
16
+ arr[index+1], arr[high] = arr[high], arr[index+1]
17
+ ret index + 1
18
+ }
19
+
20
+ // Sorts the specified range within the array
21
+ fn QuicksortRange[T: ordered](mut arr: []T, low: int, high: int) {
22
+ if len(arr) <= 1 {
23
+ ret
24
+ }
25
+
26
+ if low < high {
27
+ pivot := Partition(arr, low, high)
28
+ QuicksortRange(arr, low, pivot-1)
29
+ QuicksortRange(arr, pivot+1, high)
30
+ }
31
+ }
32
+
33
+ // Sorts the entire array.
34
+ fn Quicksort[T: ordered](mut arr: []T): []T {
35
+ QuicksortRange(arr, 0, len(arr)-1)
36
+ ret arr
37
+ }
Original file line number Diff line number Diff line change @@ -138,4 +138,9 @@ fn testPancake(t: &testing::T) {
138
138
#test
139
139
fn testShell(t: &testing::T) {
140
140
testGeneral(t, Shell[int])
141
+ }
142
+
143
+ #test
144
+ fn testQuicksort(t: &testing::T) {
145
+ testGeneral(t, Quicksort[int])
141
146
}
You can’t perform that action at this time.
0 commit comments