quick sort

This commit is contained in:
agra
2026-02-10 18:58:04 +02:00
parent a6f0276fa5
commit 3fde080092
8 changed files with 326 additions and 30 deletions

43
examples/23-quicksort.sx Normal file
View File

@@ -0,0 +1,43 @@
#import "modules/std.sx";
quickSort :: (items: []$T) {
partition :: (items: []T, lo: s32, hi: s32) -> s32 {
pivot := items[hi];
i := lo - 1;
j := lo;
while j < hi {
if items[j] < pivot {
i += 1;
tmp := items[i];
items[i] = items[j];
items[j] = tmp;
}
j += 1;
}
i += 1;
tmp := items[i];
items[i] = items[hi];
items[hi] = tmp;
i;
}
sort :: (items: []T, lo: s32, hi: s32) {
if lo < hi {
pi := partition(items, lo, hi);
sort(items, lo, pi - 1);
sort(items, pi + 1, hi);
}
}
sort(items, 0, items.len - 1);
}
main :: () {
arr := []s32.[1, 2, 3, 5, 2, 2, 3, 4, 5, 6, 6, 1];
quickSort(arr);
for arr {
if it_index > 0 { write(", "); }
print("{}", it);
}
write("\n");
}