-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
|
||
/// quickSort is qsort from "The C Programming Language". | ||
/// | ||
/// > Our version of quicksort is not the fastest possible, | ||
/// > but it's one of the simplest. | ||
/// | ||
pub fun quickSort(_ items: &[AnyStruct], isLess: ((Int, Int): Bool)) { | ||
|
||
fun quickSortPart(leftIndex: Int, rightIndex: Int) { | ||
|
||
if leftIndex >= rightIndex { | ||
return | ||
} | ||
|
||
let pivotIndex = (leftIndex + rightIndex) / 2 | ||
|
||
items[pivotIndex] <-> items[leftIndex] | ||
|
||
var lastIndex = leftIndex | ||
var index = leftIndex + 1 | ||
while index <= rightIndex { | ||
if isLess(index, leftIndex) { | ||
lastIndex = lastIndex + 1 | ||
items[lastIndex] <-> items[index] | ||
} | ||
index = index + 1 | ||
} | ||
|
||
items[leftIndex] <-> items[lastIndex] | ||
|
||
quickSortPart(leftIndex: leftIndex, rightIndex: lastIndex - 1) | ||
quickSortPart(leftIndex: lastIndex + 1, rightIndex: rightIndex) | ||
} | ||
|
||
quickSortPart( | ||
leftIndex: 0, | ||
rightIndex: items.length - 1 | ||
) | ||
} | ||
|
||
pub fun main() { | ||
let items = [5, 3, 7, 6, 2, 9] | ||
quickSort( | ||
&items as &[AnyStruct], | ||
isLess: fun (i: Int, j: Int): Bool { | ||
return items[i] < items[j] | ||
} | ||
) | ||
log(items) | ||
} |