Skip to content

Commit

Permalink
add sort/quicksort
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Oct 13, 2024
1 parent 2cc180a commit f55220e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
37 changes: 37 additions & 0 deletions sort/quicksort.jule
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// description: Implementation of in-place quicksort algorithm
// details:
// A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)
// author(s) [Taj](https://github.com/tjgurwara99)

fn Partition[T: ordered](mut arr: []T, low: int, high: int): int {
mut index := low - 1
pivotElement := arr[high]
mut i := low
for i < high; i++ {
if arr[i] <= pivotElement {
index += 1
arr[index], arr[i] = arr[i], arr[index]
}
}
arr[index+1], arr[high] = arr[high], arr[index+1]
ret index + 1
}

// Sorts the specified range within the array
fn QuicksortRange[T: ordered](mut arr: []T, low: int, high: int) {
if len(arr) <= 1 {
ret
}

if low < high {
pivot := Partition(arr, low, high)
QuicksortRange(arr, low, pivot-1)
QuicksortRange(arr, pivot+1, high)
}
}

// Sorts the entire array.
fn Quicksort[T: ordered](mut arr: []T): []T {
QuicksortRange(arr, 0, len(arr)-1)
ret arr
}
5 changes: 5 additions & 0 deletions sort/testcases_test.jule
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,9 @@ fn testPancake(t: &testing::T) {
#test
fn testShell(t: &testing::T) {
testGeneral(t, Shell[int])
}

#test
fn testQuicksort(t: &testing::T) {
testGeneral(t, Quicksort[int])
}

0 comments on commit f55220e

Please sign in to comment.