Skip to content

Commit f55220e

Browse files
committed
add sort/quicksort
1 parent 2cc180a commit f55220e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

sort/quicksort.jule

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

sort/testcases_test.jule

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,9 @@ fn testPancake(t: &testing::T) {
138138
#test
139139
fn testShell(t: &testing::T) {
140140
testGeneral(t, Shell[int])
141+
}
142+
143+
#test
144+
fn testQuicksort(t: &testing::T) {
145+
testGeneral(t, Quicksort[int])
141146
}

0 commit comments

Comments
 (0)