Merge branch 'krahets:master' into master

pull/253/head
Zero 2 years ago committed by GitHub
commit d3caf8198a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -24,7 +24,7 @@ func newHeap() *maxHeap {
/* 构造函数,根据切片建堆 */ /* 构造函数,根据切片建堆 */
func newMaxHeap(nums []any) *maxHeap { func newMaxHeap(nums []any) *maxHeap {
// 所有元素入 // 将列表元素原封不动添加进
h := &maxHeap{data: nums} h := &maxHeap{data: nums}
for i := len(h.data) - 1; i >= 0; i-- { for i := len(h.data) - 1; i >= 0; i-- {
// 堆化除叶结点以外的其他所有结点 // 堆化除叶结点以外的其他所有结点

@ -20,7 +20,7 @@ class MaxHeap {
/* 构造函数,根据输入列表建堆 */ /* 构造函数,根据输入列表建堆 */
public MaxHeap(List<Integer> nums) { public MaxHeap(List<Integer> nums) {
// 所有元素入 // 将列表元素原封不动添加进
maxHeap = new ArrayList<>(nums); maxHeap = new ArrayList<>(nums);
// 堆化除叶结点以外的其他所有结点 // 堆化除叶结点以外的其他所有结点
for (int i = parent(size() - 1); i >= 0; i--) { for (int i = parent(size() - 1); i >= 0; i--) {

@ -202,6 +202,19 @@ pub fn build(b: *std.build.Builder) void {
const run_step_heap = b.step("run_heap", "Run heap"); const run_step_heap = b.step("run_heap", "Run heap");
run_step_heap.dependOn(&run_cmd_heap.step); run_step_heap.dependOn(&run_cmd_heap.step);
// Source File: "chapter_heap/my_heap.zig"
// Run Command: zig build run_my_heap
const exe_my_heap = b.addExecutable("my_heap", "chapter_heap/my_heap.zig");
exe_my_heap.addPackagePath("include", "include/include.zig");
exe_my_heap.setTarget(target);
exe_my_heap.setBuildMode(mode);
exe_my_heap.install();
const run_cmd_my_heap = exe_my_heap.run();
run_cmd_my_heap.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_my_heap.addArgs(args);
const run_step_my_heap = b.step("run_my_heap", "Run my_heap");
run_step_my_heap.dependOn(&run_cmd_my_heap.step);
// Section: "Linear Search" // Section: "Linear Search"
// Source File: "chapter_searching/linear_search.zig" // Source File: "chapter_searching/linear_search.zig"
// Run Command: zig build run_linear_search // Run Command: zig build run_linear_search

@ -0,0 +1,190 @@
// File: my_heap.zig
// Created Time: 2023-01-14
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
//
//
pub fn MaxHeap(comptime T: type) type {
return struct {
const Self = @This();
maxHeap: ?std.ArrayList(T) = null, // 使
//
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []const T) !void {
if (self.maxHeap != null) return;
self.maxHeap = std.ArrayList(T).init(allocator);
//
try self.maxHeap.?.appendSlice(nums);
//
var i: usize = parent(self.size() - 1) + 1;
while (i > 0) : (i -= 1) {
try self.siftDown(i - 1);
}
}
//
pub fn deinit(self: *Self) void {
if (self.maxHeap != null) self.maxHeap.?.deinit();
}
//
fn left(i: usize) usize {
return 2 * i + 1;
}
//
fn right(i: usize) usize {
return 2 * i + 2;
}
//
fn parent(i: usize) usize {
// return (i - 1) / 2; //
return @divFloor(i - 1, 2);
}
//
fn swap(self: *Self, i: usize, j: usize) !void {
var a = self.maxHeap.?.items[i];
var b = self.maxHeap.?.items[j];
var tmp = a;
try self.maxHeap.?.replaceRange(i, 1, &[_]T{b});
try self.maxHeap.?.replaceRange(j, 1, &[_]T{tmp});
}
//
pub fn size(self: *Self) usize {
return self.maxHeap.?.items.len;
}
//
pub fn isEmpty(self: *Self) bool {
return self.size() == 0;
}
// 访
pub fn peek(self: *Self) T {
return self.maxHeap.?.items[0];
}
//
pub fn push(self: *Self, val: T) !void {
//
try self.maxHeap.?.append(val);
//
try self.siftUp(self.size() - 1);
}
// i
fn siftUp(self: *Self, i_: usize) !void {
var i = i_;
while (true) {
// i
var p = parent(i);
//
if (p < 0 or self.maxHeap.?.items[i] <= self.maxHeap.?.items[p]) break;
//
try self.swap(i, p);
//
i = p;
}
}
//
pub fn poll(self: *Self) !T {
//
if (self.isEmpty()) unreachable;
//
try self.swap(0, self.size() - 1);
//
var val = self.maxHeap.?.pop();
//
try self.siftDown(0);
//
return val;
}
// i
fn siftDown(self: *Self, i_: usize) !void {
var i = i_;
while (true) {
// i, l, r ma
var l = left(i);
var r = right(i);
var ma = i;
if (l < self.size() and self.maxHeap.?.items[l] > self.maxHeap.?.items[ma]) ma = l;
if (r < self.size() and self.maxHeap.?.items[r] > self.maxHeap.?.items[ma]) ma = r;
// i l, r
if (ma == i) break;
//
try self.swap(i, ma);
//
i = ma;
}
}
fn lessThan(context: void, a: T, b: T) std.math.Order {
_ = context;
return std.math.order(a, b);
}
fn greaterThan(context: void, a: T, b: T) std.math.Order {
return lessThan(context, a, b).invert();
}
//
pub fn print(self: *Self, mem_allocator: std.mem.Allocator) !void {
const PQgt = std.PriorityQueue(T, void, greaterThan);
var queue = PQgt.init(std.heap.page_allocator, {});
defer queue.deinit();
try queue.addSlice(self.maxHeap.?.items);
try inc.PrintUtil.printHeap(T, mem_allocator, queue);
}
};
}
// Driver Code
pub fn main() !void {
//
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer mem_arena.deinit();
const mem_allocator = mem_arena.allocator();
//
var maxHeap = MaxHeap(i32){};
try maxHeap.init(std.heap.page_allocator, &[_]i32{ 9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2 });
defer maxHeap.deinit();
std.debug.print("\n输入列表并建堆后\n", .{});
try maxHeap.print(mem_allocator);
//
var peek = maxHeap.peek();
std.debug.print("\n堆顶元素为 {}\n", .{peek});
//
const val = 7;
try maxHeap.push(val);
std.debug.print("\n元素 {} 入堆后\n", .{val});
try maxHeap.print(mem_allocator);
//
peek = try maxHeap.poll();
std.debug.print("\n堆顶元素 {} 出堆后\n", .{peek});
try maxHeap.print(mem_allocator);
//
var size = maxHeap.size();
std.debug.print("\n堆元素数量为 {}", .{size});
//
var isEmpty = maxHeap.isEmpty();
std.debug.print("\n堆是否为空 {}\n", .{isEmpty});
const getchar = try std.io.getStdIn().reader().readByte();
_ = getchar;
}

@ -710,10 +710,10 @@ comments: true
```go title="my_heap.go" ```go title="my_heap.go"
/* 构造函数,根据切片建堆 */ /* 构造函数,根据切片建堆 */
func newMaxHeap(nums []any) *maxHeap { func newMaxHeap(nums []any) *maxHeap {
// 所有元素入 // 将列表元素原封不动添加进
h := &maxHeap{data: nums} h := &maxHeap{data: nums}
// 堆化除叶结点以外的其他所有结点
for i := len(h.data) - 1; i >= 0; i-- { for i := len(h.data) - 1; i >= 0; i-- {
// 堆化除叶结点以外的其他所有结点
h.siftDown(i) h.siftDown(i)
} }
return h return h

@ -228,7 +228,7 @@ comments: true
**稳定排序**:不交换相等元素。 **稳定排序**:不交换相等元素。
**自适排序**:引入 `flag` 优化后(见下文),最佳时间复杂度为 $O(N)$ 。 **自适排序**:引入 `flag` 优化后(见下文),最佳时间复杂度为 $O(N)$ 。
## 效率优化 ## 效率优化

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Loading…
Cancel
Save