mirror of
https://github.com/krahets/hello-algo.git
synced 2026-12-01 00:39:05 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
61
en/codes/zig/chapter_sorting/bubble_sort.zig
Normal file
61
en/codes/zig/chapter_sorting/bubble_sort.zig
Normal file
@@ -0,0 +1,61 @@
|
||||
// File: bubble_sort.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Bubble sort
|
||||
fn bubbleSort(nums: []i32) void {
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
var i: usize = nums.len - 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
var j: usize = 0;
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
while (j < i) : (j += 1) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
var tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bubble sort (flag optimization)
|
||||
fn bubbleSortWithFlag(nums: []i32) void {
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
var i: usize = nums.len - 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
var flag = false; // Initialize the flag
|
||||
var j: usize = 0;
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
while (j < i) : (j += 1) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
var tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
if (!flag) break; // Exit immediately if this pass made no swaps
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var nums = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSort(&nums);
|
||||
std.debug.print("After bubble sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
var nums1 = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSortWithFlag(&nums1);
|
||||
std.debug.print("\nAfter bubble sort, nums1 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums1);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
31
en/codes/zig/chapter_sorting/insertion_sort.zig
Normal file
31
en/codes/zig/chapter_sorting/insertion_sort.zig
Normal file
@@ -0,0 +1,31 @@
|
||||
// File: insertion_sort.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Insertion sort
|
||||
fn insertionSort(nums: []i32) void {
|
||||
// Outer loop: the sorted range is [0, i-1]
|
||||
var i: usize = 1;
|
||||
while (i < nums.len) : (i += 1) {
|
||||
var base = nums[i];
|
||||
var j: usize = i;
|
||||
// Inner loop: insert base at the correct position in the sorted range [0, i-1]
|
||||
while (j >= 1 and nums[j - 1] > base) : (j -= 1) {
|
||||
nums[j] = nums[j - 1]; // Move nums[j - 1] one position to the right
|
||||
}
|
||||
nums[j] = base; // Place base at the correct position
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var nums = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
insertionSort(&nums);
|
||||
std.debug.print("After insertion sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
67
en/codes/zig/chapter_sorting/merge_sort.zig
Normal file
67
en/codes/zig/chapter_sorting/merge_sort.zig
Normal file
@@ -0,0 +1,67 @@
|
||||
// File: merge_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Merge the left and right subarrays
|
||||
// Left subarray range: [left, mid]
|
||||
// Right subarray range: [mid + 1, right]
|
||||
fn merge(nums: []i32, left: usize, mid: usize, right: usize) !void {
|
||||
// Initialize the auxiliary array
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var tmp = try mem_allocator.alloc(i32, right + 1 - left);
|
||||
std.mem.copy(i32, tmp, nums[left..right+1]);
|
||||
// Start and end indices of the left subarray in tmp
|
||||
var leftStart = left - left;
|
||||
var leftEnd = mid - left;
|
||||
// Start and end indices of the right subarray in tmp
|
||||
var rightStart = mid + 1 - left;
|
||||
var rightEnd = right - left;
|
||||
// i and j point to the first elements of the left and right subarrays, respectively
|
||||
var i = leftStart;
|
||||
var j = rightStart;
|
||||
// Merge the left and right subarrays by overwriting the original array nums
|
||||
var k = left;
|
||||
while (k <= right) : (k += 1) {
|
||||
// If the left subarray has been exhausted, take an element from the right subarray and increment j
|
||||
if (i > leftEnd) {
|
||||
nums[k] = tmp[j];
|
||||
j += 1;
|
||||
// Otherwise, if the right subarray is exhausted or the left element is no greater than the right element, take the left element and increment i
|
||||
} else if (j > rightEnd or tmp[i] <= tmp[j]) {
|
||||
nums[k] = tmp[i];
|
||||
i += 1;
|
||||
// Otherwise, both subarrays still have elements and the left element is larger, so take the right element and increment j
|
||||
} else {
|
||||
nums[k] = tmp[j];
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge sort
|
||||
fn mergeSort(nums: []i32, left: usize, right: usize) !void {
|
||||
// Base case
|
||||
if (left >= right) return; // Stop recursing when the subarray has at most one element
|
||||
// Divide phase
|
||||
var mid = left + (right - left) / 2; // Calculate the midpoint
|
||||
try mergeSort(nums, left, mid); // Recurse on the left subarray
|
||||
try mergeSort(nums, mid + 1, right); // Recurse on the right subarray
|
||||
// Merge phase
|
||||
try merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Merge sort
|
||||
var nums = [_]i32{ 7, 3, 2, 6, 0, 1, 5, 4 };
|
||||
try mergeSort(&nums, 0, nums.len - 1);
|
||||
std.debug.print("After merge sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
162
en/codes/zig/chapter_sorting/quick_sort.zig
Normal file
162
en/codes/zig/chapter_sorting/quick_sort.zig
Normal file
@@ -0,0 +1,162 @@
|
||||
// File: quick_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Quick sort implementation
|
||||
const QuickSort = struct {
|
||||
|
||||
// Swap the elements
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// Two-pointer partitioning
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// Use nums[left] as the pivot
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
// Quick sort
|
||||
pub fn quickSort(nums: []i32, left: usize, right: usize) void {
|
||||
// Stop when the current subarray has at most one element
|
||||
if (left >= right) return;
|
||||
// Two-pointer partitioning
|
||||
var pivot = partition(nums, left, right);
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
};
|
||||
|
||||
// Quick sort implementation (median-of-three pivot optimization)
|
||||
const QuickSortMedian = struct {
|
||||
|
||||
// Swap the elements
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// Select the median of three candidate elements
|
||||
pub fn medianThree(nums: []i32, left: usize, mid: usize, right: usize) usize {
|
||||
var l = nums[left];
|
||||
var m = nums[mid];
|
||||
var r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
return mid; // m lies between l and r
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l lies between m and r
|
||||
return right;
|
||||
}
|
||||
|
||||
// Two-pointer partitioning (median of three)
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// Select the median of three candidate elements
|
||||
var med = medianThree(nums, left, (left + right) / 2, right);
|
||||
// Swap the median into the leftmost position of the current subarray
|
||||
swap(nums, left, med);
|
||||
// Use nums[left] as the pivot
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
// Quick sort
|
||||
pub fn quickSort(nums: []i32, left: usize, right: usize) void {
|
||||
// Stop when the current subarray has at most one element
|
||||
if (left >= right) return;
|
||||
// Two-pointer partitioning
|
||||
var pivot = partition(nums, left, right);
|
||||
if (pivot == 0) return;
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
};
|
||||
|
||||
// Quick sort implementation (recursion-depth optimization)
|
||||
const QuickSortTailCall = struct {
|
||||
|
||||
// Swap the elements
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// Two-pointer partitioning
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// Use nums[left] as the pivot
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
// Quick sort (recursion depth optimization)
|
||||
pub fn quickSort(nums: []i32, left_: usize, right_: usize) void {
|
||||
var left = left_;
|
||||
var right = right_;
|
||||
// Stop when the current subarray has at most one element
|
||||
while (left < right) {
|
||||
// Perform two-pointer partitioning
|
||||
var pivot = partition(nums, left, right);
|
||||
// Apply quick sort to the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
quickSort(nums, left, pivot - 1); // Recursively sort the left subarray
|
||||
left = pivot + 1; // The remaining unsorted range is [pivot + 1, right]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // The remaining unsorted range is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Quick sort
|
||||
var nums = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSort.quickSort(&nums, 0, nums.len - 1);
|
||||
std.debug.print("After quick sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
// Quick sort (median pivot optimization)
|
||||
var nums1 = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortMedian.quickSort(&nums1, 0, nums1.len - 1);
|
||||
std.debug.print("\nAfter quick sort (median-of-three pivot optimization), nums1 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums1);
|
||||
|
||||
// Quick sort (recursion depth optimization)
|
||||
var nums2 = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortTailCall.quickSort(&nums2, 0, nums2.len - 1);
|
||||
std.debug.print("\nAfter quick sort (recursion-depth optimization), nums2 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums2);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
77
en/codes/zig/chapter_sorting/radix_sort.zig
Normal file
77
en/codes/zig/chapter_sorting/radix_sort.zig
Normal file
@@ -0,0 +1,77 @@
|
||||
// File: radix_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Get the k-th digit of num, where exp = 10^(k-1)
|
||||
fn digit(num: i32, exp: i32) i32 {
|
||||
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
|
||||
return @mod(@divFloor(num, exp), 10);
|
||||
}
|
||||
|
||||
// Counting sort (sort nums by the k-th digit)
|
||||
fn countingSortDigit(nums: []i32, exp: i32) !void {
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs length 10
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
// defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var counter = try mem_allocator.alloc(usize, 10);
|
||||
@memset(counter, 0);
|
||||
var n = nums.len;
|
||||
// Count the occurrences of each digit from 0 to 9
|
||||
for (nums) |num| {
|
||||
var d: u32 = @bitCast(digit(num, exp)); // Get the kth digit of the current element and store it in d
|
||||
counter[d] += 1; // Count the occurrences of digit d
|
||||
}
|
||||
// Compute prefix sums to convert occurrence counts into array positions
|
||||
var i: usize = 1;
|
||||
while (i < 10) : (i += 1) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse and place each element into res according to the bucket counts
|
||||
var res = try mem_allocator.alloc(i32, n);
|
||||
i = n - 1;
|
||||
while (i >= 0) : (i -= 1) {
|
||||
var d: u32 = @bitCast(digit(nums[i], exp));
|
||||
var j = counter[d] - 1; // Get the destination index j for digit d in the array
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d] -= 1; // Decrease the count for d by 1
|
||||
if (i == 0) break;
|
||||
}
|
||||
// Overwrite the original array nums with the result
|
||||
i = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Radix sort
|
||||
fn radixSort(nums: []i32) !void {
|
||||
// Get the largest array element to determine the maximum number of digits
|
||||
var m: i32 = std.math.minInt(i32);
|
||||
for (nums) |num| {
|
||||
if (num > m) m = num;
|
||||
}
|
||||
// Process digits from least significant to most significant
|
||||
var exp: i32 = 1;
|
||||
while (exp <= m) : (exp *= 10) {
|
||||
// Apply counting sort to the k-th digit of the array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// That is, exp = 10^(k-1)
|
||||
try countingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Radix sort
|
||||
var nums = [_]i32{ 23, 12, 3, 4, 788, 192 };
|
||||
try radixSort(&nums);
|
||||
std.debug.print("After radix sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
Reference in New Issue
Block a user