Sorting algorithms/Quicksort: Difference between revisions
→{{header|zig}}: new version based on Rust, with generic comparator function, annotate versions
imported>Rcmlz |
(→{{header|zig}}: new version based on Rust, with generic comparator function, annotate versions) |
||
Line 10,325:
Full example with test/debug data for ZX Spectrum is at [[https://gist.github.com/ped7g/0c4e94796b474994ed88d0bdd1bf2f25 github]].
=={{header|
{{trans|Rust}}
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1390+94cee4fb2
<syntaxhighlight lang="zig">const std = @import("std");
pub fn
if (arr.len < 2) return;
var right: usize = arr.len - 1;▼
const pivot_index = partition(T, arr, compareFn);
while (left <= right) {▼
quickSort(T, arr[0..pivot_index], compareFn);
quickSort(T, arr[pivot_index + 1 .. arr.len], compareFn);
left += 1;▼
}▼
}▼
fn partition(comptime T: type, arr: []T, comptime compareFn: fn (T, T) bool) usize {
right -= 1;▼
const pivot_index = arr.len
if (left <= right) {▼
std.mem.swap(T,
var store_index: usize
for (arr[0 .. arr.len - 1]) |*elem_ptr| {
if (compareFn(elem_ptr.*, arr[last_index])) {
std.mem.swap(T, elem_ptr, &arr[store_index]);
}
}
return store_index;
}</syntaxhighlight>
▲}
<syntaxhighlight lang="zig">const std = @import("std");
pub fn main() !void {▼
var arr: [10]LIST_TYPE = [_]LIST_TYPE{ 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 };▼
const print
}▼
std.debug.print("\n", .{});▼
print("Sort numbers in ascending
quickSort(i16, &arr, struct {
std.debug.print("\n", .{});▼
▲ }
}.sortFn);
print("Sort numbers in descending order.\n", .{});
quickSort(i16, &arr, struct {
fn sortFn(left: i16, right: i16) bool {
▲ }
}.sortFn);
}</syntaxhighlight>
{{out}}
<pre>
Before: { 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 }
-31 0 1 2 2 4 65 83 99 782▼
Sort numbers in ascending order.
▲After: { -31, 0, 1, 2, 2, 4, 65, 83, 99, 782 }
Sort numbers in descending order.
After: { 782, 99, 83, 65, 4, 2, 2, 1, 0, -31 }
</pre>
|