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