From ee63302d4302a97997bb7cb0128d7669775e2ea0 Mon Sep 17 00:00:00 2001 From: cloudnative0x0 <> Date: Thu, 1 Oct 2026 14:55:33 +0300 Subject: [PATCH] new structure added. --- binary_heap/README.md | 219 +++++++++++++++++++++++++++++++++++++++ binary_heap/heap.go | 128 +++++++++++++++++++++++ binary_heap/heap_test.go | 164 +++++++++++++++++++++++++++++ 3 files changed, 511 insertions(+) create mode 100644 binary_heap/README.md create mode 100644 binary_heap/heap.go create mode 100644 binary_heap/heap_test.go diff --git a/binary_heap/README.md b/binary_heap/README.md new file mode 100644 index 0000000..ff9e36d --- /dev/null +++ b/binary_heap/README.md @@ -0,0 +1,219 @@ +# Binary Heap + +

+ Русский ・ English +

+ +--- + +## Русский + +Бинарная куча (binary heap) — это почти полное бинарное дерево, в котором каждый родитель имеет приоритет не ниже своих детей. В **min-heap** наверху всегда минимальный элемент, в **max-heap** — максимальный. + +Куча не хранит все значения в отсортированном порядке. Она гарантирует только, что лучший по приоритету элемент находится в корне и может быть получен за O(1). Благодаря этому вставка и извлечение приоритетного элемента выполняются за O(log n), а не требуют полной сортировки после каждого изменения. + +### Внутреннее устройство + +Дерево хранится в непрерывном срезе `data`, без указателей между узлами. Для элемента с индексом `i`: + +- родитель находится по индексу `(i-1)/2`; +- левый ребёнок — `2*i+1`; +- правый ребёнок — `2*i+2`. + +Например, массив `[1, 3, 2, 8, 5]` представляет min-heap: + +```text + 1 + / \ + 3 2 + / \ + 8 5 +``` + +Функция `less(a, b)` определяет приоритет. Если она возвращает `true`, значение `a` должно находиться ближе к корню, чем `b`. Поэтому одна реализация поддерживает min-heap, max-heap и пользовательские типы. + +**Вставка (`Push`).** Новый элемент добавляется в конец среза, затем поднимается вверх (`siftUp`), пока имеет больший приоритет, чем родитель. + +**Извлечение (`Pop`).** Корень сохраняется как результат, последний элемент переносится на его место и опускается вниз (`siftDown`) через ребёнка с более высоким приоритетом. + +**Построение (`New`).** Готовый набор значений копируется, после чего внутренние узлы просеиваются снизу вверх. Алгоритм Флойда строит кучу за O(n), что быстрее последовательных O(n log n) вставок. + +### Зачем нужна бинарная куча + +Главный бизнес-сценарий — **очередь с приоритетом**: сначала обрабатывается не самая старая задача, а самая важная. Примеры: диспетчеризация фоновых заданий, выбор ближайшего события по времени, планирование запросов, обработка инцидентов, алгоритмы Дейкстры и Прима, поиск top-K элементов и объединение отсортированных потоков. + +Куча хорошо подходит, когда постоянно нужен один экстремальный элемент. Если требуется быстрый поиск произвольного значения или полностью отсортированный обход без разрушения структуры, нужны другие структуры. + +### Использование + +Min-heap для целых чисел: + +```go +h := NewMinHeap(7, 2, 9) +h.Push(1) + +top, _ := h.Peek() // 1; куча не меняется +value, _ := h.Pop() // 1; элемент удалён +size := h.Len() // 3 +``` + +Max-heap: + +```go +h := NewMaxHeap(7, 2, 9) +value, _ := h.Pop() // 9 +``` + +Пользовательский приоритет: + +```go +type Job struct { + Name string + Priority int +} + +h := New(func(a, b Job) bool { + return a.Priority > b.Priority +}) + +h.Push(Job{Name: "email", Priority: 1}) +h.Push(Job{Name: "incident", Priority: 10}) +next, _ := h.Pop() // incident +``` + +Пустые `Peek` и `Pop` возвращают `ErrEmpty`. Конструктор паникует при `nil` вместо компаратора, потому что без правила приоритета поддерживать инвариант невозможно. + +### Операции и сложность + +Пусть `n` — число элементов в куче. + +| Операция | Время | Доп. память | Описание | +|---|---:|---:|---| +| `New(less, values...)` | O(n) | O(n) | скопировать значения и построить кучу снизу вверх | +| `NewMinHeap(values...)` | O(n) | O(n) | создать min-heap целых чисел | +| `NewMaxHeap(values...)` | O(n) | O(n) | создать max-heap целых чисел | +| `Push(value)` | O(log n) | O(1)* | добавить значение и поднять его | +| `Peek()` | O(1) | O(1) | вернуть корень без удаления | +| `Pop()` | O(log n) | O(1) | удалить корень и восстановить инвариант | +| `Len()` / `IsEmpty()` | O(1) | O(1) | получить размер или проверить пустоту | + +\* Амортизированно вставка может расширить внутренний срез и выделить O(n) памяти, но само просеивание работает на месте. + +### Сборка и тестирование + +```bash +go test -v ./binary_heap +``` + +Тесты проверяют min/max-порядок, дубликаты, отрицательные числа, пользовательский тип, пустую кучу, независимость от исходного среза и 20 000 случайных операций со сравнением против эталонной модели. + +--- + +## English + +A binary heap is an almost complete binary tree in which every parent has at least as much priority as its children. A **min-heap** always keeps the smallest element on top; a **max-heap** keeps the largest one there. + +A heap does not keep every value fully sorted. It only guarantees that the highest-priority value is at the root and can be read in O(1). This makes insertion and priority removal O(log n), without sorting the entire collection after every change. + +### Internal layout + +The tree is stored in one contiguous `data` slice with no pointers between nodes. For an item at index `i`: + +- its parent is at `(i-1)/2`; +- its left child is at `2*i+1`; +- its right child is at `2*i+2`. + +For example, `[1, 3, 2, 8, 5]` represents this min-heap: + +```text + 1 + / \ + 3 2 + / \ + 8 5 +``` + +The `less(a, b)` function defines priority. If it returns `true`, `a` belongs closer to the root than `b`. This lets one implementation support min-heaps, max-heaps, and application-specific types. + +**Insertion (`Push`).** A new item is appended to the slice and moves upward (`siftUp`) while it has more priority than its parent. + +**Removal (`Pop`).** The root is saved as the result, the final item moves into its place, and then moves downward (`siftDown`) through the higher-priority child. + +**Construction (`New`).** The input values are copied, then internal nodes are sifted from the bottom upward. Floyd's algorithm builds the heap in O(n), faster than O(n log n) repeated insertion. + +### Why a binary heap is useful + +The primary business use case is a **priority queue**: the most important task, rather than the oldest task, is processed first. Examples include background-job dispatch, selecting the next timed event, request scheduling, incident handling, Dijkstra's and Prim's algorithms, top-K queries, and merging sorted streams. + +A heap fits workloads that repeatedly need one extreme value. When arbitrary-value lookup or a fully sorted non-destructive traversal is required, a different structure is usually a better choice. + +### Usage + +An integer min-heap: + +```go +h := NewMinHeap(7, 2, 9) +h.Push(1) + +top, _ := h.Peek() // 1; heap is unchanged +value, _ := h.Pop() // 1; item is removed +size := h.Len() // 3 +``` + +A max-heap: + +```go +h := NewMaxHeap(7, 2, 9) +value, _ := h.Pop() // 9 +``` + +Application-specific priority: + +```go +type Job struct { + Name string + Priority int +} + +h := New(func(a, b Job) bool { + return a.Priority > b.Priority +}) + +h.Push(Job{Name: "email", Priority: 1}) +h.Push(Job{Name: "incident", Priority: 10}) +next, _ := h.Pop() // incident +``` + +Empty `Peek` and `Pop` calls return `ErrEmpty`. The constructor panics for a `nil` comparator because the invariant cannot be maintained without a priority rule. + +### Operations and complexity + +Let `n` be the number of values in the heap. + +| Operation | Time | Extra space | Description | +|---|---:|---:|---| +| `New(less, values...)` | O(n) | O(n) | copy the values and build the heap bottom-up | +| `NewMinHeap(values...)` | O(n) | O(n) | create an integer min-heap | +| `NewMaxHeap(values...)` | O(n) | O(n) | create an integer max-heap | +| `Push(value)` | O(log n) | O(1)* | add a value and move it upward | +| `Peek()` | O(1) | O(1) | return the root without removal | +| `Pop()` | O(log n) | O(1) | remove the root and restore the invariant | +| `Len()` / `IsEmpty()` | O(1) | O(1) | read the size or check for emptiness | + +\* Amortized insertion may grow the backing slice and allocate O(n) memory, while the sifting operation itself works in place. + +### Build and test + +```bash +go test -v ./binary_heap +``` + +Tests cover min/max ordering, duplicates, negative numbers, a custom type, empty-heap behavior, independence from the input slice, and 20,000 random operations checked against a reference model. + +--- + +
+ +> Куча не знает полного порядка. Она знает только, кто должен быть следующим, — и часто именно этого достаточно для быстрой системы. +> +> *A heap does not know the complete order. It only knows who should come next—and that is often all a fast system needs.* diff --git a/binary_heap/heap.go b/binary_heap/heap.go new file mode 100644 index 0000000..b87bd4f --- /dev/null +++ b/binary_heap/heap.go @@ -0,0 +1,128 @@ +// Package binary_heap implements a generic array-backed binary heap. +package binary_heap + +import "errors" + +// ErrEmpty is returned when Peek or Pop is called on an empty heap. +var ErrEmpty = errors.New("binary heap is empty") + +// Heap is a binary heap ordered by less. If less(a, b) is true, a has higher +// priority than b and is placed closer to the root. +type Heap[T any] struct { + data []T + less func(a, b T) bool +} + +// New creates a heap from values in O(n) time using bottom-up heapification. +// It panics when less is nil because a heap cannot maintain an order without +// a comparator. +func New[T any](less func(a, b T) bool, values ...T) *Heap[T] { + if less == nil { + panic("binary_heap: nil comparator") + } + + h := &Heap[T]{ + data: append([]T(nil), values...), + less: less, + } + + for i := len(h.data)/2 - 1; i >= 0; i-- { + h.siftDown(i) + } + + return h +} + +// NewMinHeap creates an integer min-heap. The smallest value has the highest +// priority and is stored at the root. +func NewMinHeap(values ...int) *Heap[int] { + return New(func(a, b int) bool { return a < b }, values...) +} + +// NewMaxHeap creates an integer max-heap. The largest value has the highest +// priority and is stored at the root. +func NewMaxHeap(values ...int) *Heap[int] { + return New(func(a, b int) bool { return a > b }, values...) +} + +// Len returns the number of values currently stored in the heap. +func (h *Heap[T]) Len() int { + return len(h.data) +} + +// IsEmpty reports whether the heap contains no values. +func (h *Heap[T]) IsEmpty() bool { + return len(h.data) == 0 +} + +// Peek returns the root without removing it. +func (h *Heap[T]) Peek() (T, error) { + if h.IsEmpty() { + var zero T + return zero, ErrEmpty + } + + return h.data[0], nil +} + +// Push inserts a value and restores the heap invariant from bottom to top. +func (h *Heap[T]) Push(value T) { + h.data = append(h.data, value) + h.siftUp(len(h.data) - 1) +} + +// Pop removes and returns the root. +func (h *Heap[T]) Pop() (T, error) { + if h.IsEmpty() { + var zero T + return zero, ErrEmpty + } + + root := h.data[0] + last := len(h.data) - 1 + h.data[0] = h.data[last] + + var zero T + h.data[last] = zero + h.data = h.data[:last] + + if len(h.data) > 0 { + h.siftDown(0) + } + + return root, nil +} + +func (h *Heap[T]) siftUp(index int) { + for index > 0 { + parent := (index - 1) / 2 + if !h.less(h.data[index], h.data[parent]) { + return + } + + h.data[index], h.data[parent] = h.data[parent], h.data[index] + index = parent + } +} + +func (h *Heap[T]) siftDown(index int) { + for { + left := 2*index + 1 + if left >= len(h.data) { + return + } + + best := left + right := left + 1 + if right < len(h.data) && h.less(h.data[right], h.data[left]) { + best = right + } + + if !h.less(h.data[best], h.data[index]) { + return + } + + h.data[index], h.data[best] = h.data[best], h.data[index] + index = best + } +} diff --git a/binary_heap/heap_test.go b/binary_heap/heap_test.go new file mode 100644 index 0000000..773b216 --- /dev/null +++ b/binary_heap/heap_test.go @@ -0,0 +1,164 @@ +package binary_heap + +import ( + "errors" + "math/rand" + "slices" + "testing" +) + +func TestMinHeapPopsAscending(t *testing.T) { + h := NewMinHeap(7, -2, 5, 5, 0, 11, -9) + want := []int{-9, -2, 0, 5, 5, 7, 11} + + got := popAll(t, h) + if !slices.Equal(got, want) { + t.Fatalf("Pop order = %v, want %v", got, want) + } +} + +func TestMaxHeapPopsDescending(t *testing.T) { + h := NewMaxHeap(7, -2, 5, 5, 0, 11, -9) + want := []int{11, 7, 5, 5, 0, -2, -9} + + got := popAll(t, h) + if !slices.Equal(got, want) { + t.Fatalf("Pop order = %v, want %v", got, want) + } +} + +func TestPushPeekLenAndIsEmpty(t *testing.T) { + h := NewMinHeap() + if !h.IsEmpty() || h.Len() != 0 { + t.Fatalf("new heap: IsEmpty=%v Len=%d, want true and 0", h.IsEmpty(), h.Len()) + } + + for _, value := range []int{8, 3, 10, 1} { + h.Push(value) + } + + if h.IsEmpty() || h.Len() != 4 { + t.Fatalf("after pushes: IsEmpty=%v Len=%d, want false and 4", h.IsEmpty(), h.Len()) + } + if got, err := h.Peek(); err != nil || got != 1 { + t.Fatalf("Peek() = (%d, %v), want (1, nil)", got, err) + } + if h.Len() != 4 { + t.Fatalf("Peek changed length to %d, want 4", h.Len()) + } +} + +func TestEmptyHeapErrors(t *testing.T) { + h := NewMinHeap() + + if got, err := h.Peek(); got != 0 || !errors.Is(err, ErrEmpty) { + t.Fatalf("Peek() = (%d, %v), want (0, ErrEmpty)", got, err) + } + if got, err := h.Pop(); got != 0 || !errors.Is(err, ErrEmpty) { + t.Fatalf("Pop() = (%d, %v), want (0, ErrEmpty)", got, err) + } +} + +func TestNewCopiesInput(t *testing.T) { + values := []int{3, 1, 2} + h := NewMinHeap(values...) + + values[0] = -100 + if got, err := h.Peek(); err != nil || got != 1 { + t.Fatalf("heap aliases constructor input: Peek() = (%d, %v)", got, err) + } +} + +func TestGenericHeapWithCustomPriority(t *testing.T) { + type job struct { + name string + priority int + } + + h := New(func(a, b job) bool { + return a.priority > b.priority + }, + job{name: "report", priority: 2}, + job{name: "incident", priority: 10}, + job{name: "email", priority: 1}, + ) + + got, err := h.Pop() + if err != nil { + t.Fatalf("Pop() error = %v", err) + } + if got.name != "incident" { + t.Fatalf("first job = %q, want incident", got.name) + } +} + +func TestNilComparatorPanics(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatal("New with nil comparator did not panic") + } + }() + + New[int](nil) +} + +func TestRandomOperationsAgainstReference(t *testing.T) { + rng := rand.New(rand.NewSource(42)) + h := NewMinHeap() + var reference []int + + for step := 0; step < 20_000; step++ { + if len(reference) == 0 || rng.Intn(3) != 0 { + value := rng.Intn(20_001) - 10_000 + h.Push(value) + reference = append(reference, value) + } else { + minIndex := 0 + for i := 1; i < len(reference); i++ { + if reference[i] < reference[minIndex] { + minIndex = i + } + } + + want := reference[minIndex] + reference[minIndex] = reference[len(reference)-1] + reference = reference[:len(reference)-1] + + got, err := h.Pop() + if err != nil || got != want { + t.Fatalf("step %d: Pop() = (%d, %v), want (%d, nil)", step, got, err, want) + } + } + + if h.Len() != len(reference) { + t.Fatalf("step %d: Len() = %d, want %d", step, h.Len(), len(reference)) + } + assertInvariant(t, h) + } +} + +func popAll(t *testing.T, h *Heap[int]) []int { + t.Helper() + + result := make([]int, 0, h.Len()) + for !h.IsEmpty() { + value, err := h.Pop() + if err != nil { + t.Fatalf("Pop() error = %v", err) + } + result = append(result, value) + } + + return result +} + +func assertInvariant[T any](t *testing.T, h *Heap[T]) { + t.Helper() + + for child := 1; child < len(h.data); child++ { + parent := (child - 1) / 2 + if h.less(h.data[child], h.data[parent]) { + t.Fatalf("heap invariant broken between parent %d and child %d", parent, child) + } + } +}