Montículo Binario y Heapsort
Montículo max/min interactivo con vista dual de matriz y árbol.
Acerca de esta herramienta
Un montículo binario (heap) es un árbol binario completo guardado en un simple array: los hijos del índice i están en 2i+1 y 2i+2, y su padre en ⌊(i−1)/2⌋. En un montículo de máximos cada padre es al menos tan grande como sus hijos (al revés en uno de mínimos), así que el elemento de la cima es siempre el máximo (o el mínimo). Es la forma estándar de implementar una cola de prioridad.
Este laboratorio dibuja el árbol y el array lado a lado y anima el flotado (sift-up) al insertar, el hundido (sift-down) al extraer, la construcción ascendente en O(n) y heapsort. Cambia entre montículo de máximos y de mínimos para ver las mismas operaciones con el orden invertido.
Cómo usar: Montículo Binario y Heapsort
- Elige montículo de máximos o de mínimos. Al cambiar, los valores actuales se reconstruyen como un montículo válido del nuevo tipo.
- Inserta un valor: se coloca al final del array y sube intercambiándose mientras supere a su padre.
- Extrae la cima: el último elemento pasa a la raíz y se hunde intercambiándose con su hijo mayor (o menor).
- Ejecuta «Construir montículo» o «Heapsort» para seguir los algoritmos completos paso a paso, con los índices del array resaltados.
Ejemplos
Insertar en un montículo de máximos
[50, 30, 40, 10, 20], insertar 45
45 se añade en el índice 5 y se intercambia con su padre 40 → [50, 30, 45, 10, 20, 40]
Extraer el máximo
[50, 30, 45, 10, 20, 40]
Devuelve 50; 40 pasa a la raíz y se hunde → [45, 30, 40, 10, 20]
Heapsort
[4, 10, 3, 5, 1]
[1, 3, 4, 5, 10]: construir un montículo de máximos y luego llevar repetidamente la raíz al final
Implementación en cinco lenguajes
El mismo algoritmo en Python, JavaScript, Java, Go y C++. Cada programa está completo y se puede ejecutar; los comentarios indican lo que imprime.
class MinHeap:
def __init__(self):
self.a = []
def push(self, x):
a = self.a
a.append(x)
i = len(a) - 1
while i > 0: # sift up
parent = (i - 1) // 2
if a[parent] <= a[i]:
break
a[parent], a[i] = a[i], a[parent]
i = parent
def pop(self):
a = self.a
top = a[0]
last = a.pop()
if a:
a[0] = last
i, n = 0, len(a)
while True: # sift down
left, right, smallest = 2 * i + 1, 2 * i + 2, i
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
break
a[i], a[smallest] = a[smallest], a[i]
i = smallest
return top
def __len__(self):
return len(self.a)
h = MinHeap()
for x in [5, 3, 8, 1, 9, 2]:
h.push(x)
print(h.a) # [1, 3, 2, 5, 9, 8]
print([h.pop() for _ in range(len(h))]) # [1, 2, 3, 5, 8, 9] class MinHeap {
constructor() {
this.a = [];
}
get size() {
return this.a.length;
}
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) { // sift up
const parent = (i - 1) >> 1;
if (a[parent] <= a[i]) break;
[a[parent], a[i]] = [a[i], a[parent]];
i = parent;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
const n = a.length;
for (;;) { // sift down
const left = 2 * i + 1, right = 2 * i + 2;
let smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest === i) break;
[a[i], a[smallest]] = [a[smallest], a[i]];
i = smallest;
}
}
return top;
}
}
const h = new MinHeap();
for (const x of [5, 3, 8, 1, 9, 2]) h.push(x);
console.log(h.a.join(', ')); // 1, 3, 2, 5, 9, 8
const sorted = [];
while (h.size > 0) sorted.push(h.pop());
console.log(sorted.join(', ')); // 1, 2, 3, 5, 8, 9 import java.util.ArrayList;
import java.util.List;
public class Main {
static class MinHeap {
final List<Integer> a = new ArrayList<>();
int size() { return a.size(); }
void push(int x) {
a.add(x);
int i = a.size() - 1;
while (i > 0) { // sift up
int parent = (i - 1) / 2;
if (a.get(parent) <= a.get(i)) break;
swap(parent, i);
i = parent;
}
}
int pop() {
int top = a.get(0);
int last = a.remove(a.size() - 1);
if (!a.isEmpty()) {
a.set(0, last);
int i = 0, n = a.size();
while (true) { // sift down
int left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && a.get(left) < a.get(smallest)) smallest = left;
if (right < n && a.get(right) < a.get(smallest)) smallest = right;
if (smallest == i) break;
swap(i, smallest);
i = smallest;
}
}
return top;
}
private void swap(int i, int j) {
int t = a.get(i);
a.set(i, a.get(j));
a.set(j, t);
}
}
public static void main(String[] args) {
MinHeap h = new MinHeap();
for (int x : new int[] {5, 3, 8, 1, 9, 2}) h.push(x);
System.out.println(h.a); // [1, 3, 2, 5, 9, 8]
List<Integer> sorted = new ArrayList<>();
while (h.size() > 0) sorted.add(h.pop());
System.out.println(sorted); // [1, 2, 3, 5, 8, 9]
}
} package main
import "fmt"
type MinHeap struct{ a []int }
func (h *MinHeap) Len() int { return len(h.a) }
func (h *MinHeap) Push(x int) {
h.a = append(h.a, x)
i := len(h.a) - 1
for i > 0 { // sift up
parent := (i - 1) / 2
if h.a[parent] <= h.a[i] {
break
}
h.a[parent], h.a[i] = h.a[i], h.a[parent]
i = parent
}
}
func (h *MinHeap) Pop() int {
a := h.a
top := a[0]
n := len(a) - 1
a[0] = a[n]
a = a[:n]
i := 0
for { // sift down
left, right, smallest := 2*i+1, 2*i+2, i
if left < n && a[left] < a[smallest] {
smallest = left
}
if right < n && a[right] < a[smallest] {
smallest = right
}
if smallest == i {
break
}
a[i], a[smallest] = a[smallest], a[i]
i = smallest
}
h.a = a
return top
}
func main() {
h := &MinHeap{}
for _, x := range []int{5, 3, 8, 1, 9, 2} {
h.Push(x)
}
fmt.Println(h.a) // [1 3 2 5 9 8]
var sorted []int
for h.Len() > 0 {
sorted = append(sorted, h.Pop())
}
fmt.Println(sorted) // [1 2 3 5 8 9]
} #include <iostream>
#include <utility>
#include <vector>
class MinHeap {
public:
std::vector<int> a;
bool empty() const { return a.empty(); }
void push(int x) {
a.push_back(x);
size_t i = a.size() - 1;
while (i > 0) { // sift up
size_t parent = (i - 1) / 2;
if (a[parent] <= a[i]) break;
std::swap(a[parent], a[i]);
i = parent;
}
}
int pop() {
int top = a[0];
a[0] = a.back();
a.pop_back();
size_t i = 0, n = a.size();
while (true) { // sift down
size_t left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest == i) break;
std::swap(a[i], a[smallest]);
i = smallest;
}
return top;
}
};
int main() {
MinHeap h;
for (int x : {5, 3, 8, 1, 9, 2}) h.push(x);
for (int x : h.a) std::cout << x << ' '; // 1 3 2 5 9 8
std::cout << '\n';
while (!h.empty()) std::cout << h.pop() << ' '; // 1 2 3 5 8 9
std::cout << '\n';
} Practica en LeetCode
Problemas clásicos que usan este algoritmo, ideales para después de explorar el laboratorio. Los enlaces abren LeetCode (en inglés).
Costes
- Consultar la cima: O(1). Insertar y extraer: O(log n), un camino de la raíz a una hoja.
- Construcción ascendente: O(n), porque la mayoría de los nodos están abajo y solo se hunden un poco.
- Heapsort: O(n log n) en todos los casos, in situ, pero no estable.
Dónde se usan los montículos
Los planificadores y las simulaciones de eventos eligen la siguiente tarea por prioridad; los algoritmos de Dijkstra y de Prim extraen el vértice más cercano; las consultas top-k mantienen un montículo de tamaño k; y la mezcla de k archivos ordenados usa un montículo con sus cabezas. La mayoría de los lenguajes incluye uno: heapq en Python, PriorityQueue en Java, std::priority_queue en C++.
Preguntas frecuentes
Respuestas a tus dudas sobre el funcionamiento y la seguridad de los datos.
¿Por qué un array en lugar de nodos y punteros?
Un montículo es siempre un árbol completo, sin huecos; la aritmética de índices sustituye a los punteros, ahorra memoria y aprovecha bien la caché.
¿Puedo buscar rápido en un montículo?
No. Encontrar un valor cualquiera cuesta O(n). Si necesitas consultas ordenadas, usa un árbol de búsqueda equilibrado.
¿Por qué construir un montículo cuesta O(n) y no O(n log n)?
El coste de hundir depende de la altura bajo el nodo. La mitad de los nodos son hojas (coste 0), una cuarta parte tiene altura 1, y así sucesivamente; la suma converge a unos 2n.
¿Mis datos están seguros con esta herramienta?
Totalmente seguros. Todo el procesamiento se ejecuta de forma local en tu navegador sin enviar información a ningún servidor.
Herramientas relacionadas
Compare ordenamiento burbuja, selección, inserción, rápido, mezcla y montículo.
Árbol binario autoequilibrado con rotaciones LL, RR, LR y RL animadas.
Visualizador interactivo de BST con inserción, eliminación y recorridos.
Proyectos destacados tech-fun.net
Explora más herramientas de IA y productividad
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.