Polish the chapter

introduction, computational complexity.
This commit is contained in:
krahets
2023-08-20 14:51:39 +08:00
parent 5fb728b3d6
commit 2626de8d0b
87 changed files with 375 additions and 371 deletions
@@ -143,37 +143,37 @@ pub fn main() !void {
std.debug.print("输入数据大小 n = {}\n", .{n});
var count = constant(n);
std.debug.print("常数阶的计算操作数量 = {}\n", .{count});
std.debug.print("常数阶的操作数量 = {}\n", .{count});
count = linear(n);
std.debug.print("线性阶的计算操作数量 = {}\n", .{count});
std.debug.print("线性阶的操作数量 = {}\n", .{count});
var nums = [_]i32{0}**n;
count = arrayTraversal(&nums);
std.debug.print("线性阶(遍历数组)的计算操作数量 = {}\n", .{count});
std.debug.print("线性阶(遍历数组)的操作数量 = {}\n", .{count});
count = quadratic(n);
std.debug.print("平方阶的计算操作数量 = {}\n", .{count});
std.debug.print("平方阶的操作数量 = {}\n", .{count});
for (&nums, 0..) |*num, i| {
num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
}
count = bubbleSort(&nums);
std.debug.print("平方阶(冒泡排序)的计算操作数量 = {}\n", .{count});
std.debug.print("平方阶(冒泡排序)的操作数量 = {}\n", .{count});
count = exponential(n);
std.debug.print("指数阶(循环实现)的计算操作数量 = {}\n", .{count});
std.debug.print("指数阶(循环实现)的操作数量 = {}\n", .{count});
count = expRecur(n);
std.debug.print("指数阶(递归实现)的计算操作数量 = {}\n", .{count});
std.debug.print("指数阶(递归实现)的操作数量 = {}\n", .{count});
count = logarithmic(@as(f32, n));
std.debug.print("对数阶(循环实现)的计算操作数量 = {}\n", .{count});
std.debug.print("对数阶(循环实现)的操作数量 = {}\n", .{count});
count = logRecur(@as(f32, n));
std.debug.print("对数阶(递归实现)的计算操作数量 = {}\n", .{count});
std.debug.print("对数阶(递归实现)的操作数量 = {}\n", .{count});
count = linearLogRecur(@as(f32, n));
std.debug.print("线性对数阶(递归实现)的计算操作数量 = {}\n", .{count});
std.debug.print("线性对数阶(递归实现)的操作数量 = {}\n", .{count});
count = factorialRecur(n);
std.debug.print("阶乘阶(递归实现)的计算操作数量 = {}\n", .{count});
std.debug.print("阶乘阶(递归实现)的操作数量 = {}\n", .{count});
_ = try std.io.getStdIn().reader().readByte();
}
+3 -3
View File
@@ -10,7 +10,7 @@ pub fn MaxHeap(comptime T: type) type {
return struct {
const Self = @This();
max_heap: ?std.ArrayList(T) = null, // 使用列表而非数组,这样无考虑扩容问题
max_heap: ?std.ArrayList(T) = null, // 使用列表而非数组,这样无考虑扩容问题
// 构造方法,根据输入列表建堆
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []const T) !void {
@@ -82,7 +82,7 @@ pub fn MaxHeap(comptime T: type) type {
while (true) {
// 获取节点 i 的父节点
var p = parent(i);
// 当“越过根节点”或“节点无修复”时,结束堆化
// 当“越过根节点”或“节点无修复”时,结束堆化
if (p < 0 or self.max_heap.?.items[i] <= self.max_heap.?.items[p]) break;
// 交换两节点
try self.swap(i, p);
@@ -115,7 +115,7 @@ pub fn MaxHeap(comptime T: type) type {
var ma = i;
if (l < self.size() and self.max_heap.?.items[l] > self.max_heap.?.items[ma]) ma = l;
if (r < self.size() and self.max_heap.?.items[r] > self.max_heap.?.items[ma]) ma = r;
// 若节点 i 最大或索引 l, r 越界,则无继续堆化,跳出
// 若节点 i 最大或索引 l, r 越界,则无继续堆化,跳出
if (ma == i) break;
// 交换两节点
try self.swap(i, ma);
+1 -1
View File
@@ -103,7 +103,7 @@ pub fn AVLTree(comptime T: type) type {
return self.leftRotate(node);
}
}
// 平衡树,无旋转,直接返回
// 平衡树,无旋转,直接返回
return node;
}