Algoritmos y estructuras de datos en JavaScript: en la práctica
En el desarrollo web moderno, el conocimiento de algoritmos y estructuras de datos no es solo una habilidad académica, sino una herramienta para crear aplicaciones rápidas y escalables. JavaScript, especialmente en el entorno Node.js, permite implementar construcciones algorítmicas tanto simples como complejas. En este artículo, analizaremos las estructuras de datos y algoritmos clave en la práctica, con ejemplos de código que se pueden usar inmediatamente en proyectos.
1. Estructuras de datos básicas: pila, cola y lista enlazada
Empecemos por lo fundamental. La pila y la cola son estructuras lineales que se utilizan a menudo en análisis sintáctico, colas de tareas y gestión del historial de acciones.
Pila (LIFO)
La pila funciona bajo el principio "último en entrar, primero en salir". La implementamos basándonos en un array:
class Stack { constructor() { this.items = []; }
push(element) { this.items.push(element); }
pop() { return this.items.pop(); }
peek() { return this.items[this.items.length - 1]; }
isEmpty() { return this.items.length === 0; }}
// Ejemplo de usoconst stack = new Stack();stack.push('Page 1');stack.push('Page 2');console.log(stack.pop()); // 'Page 2'Cola (FIFO)
La cola es útil para procesar tareas en orden de llegada. Implementación usando una clase:
class Queue { constructor() { this.items = {}; this.front = 0; this.rear = 0; }
enqueue(element) { this.items[this.rear] = element; this.rear++; }
dequeue() { const item = this.items[this.front]; delete this.items[this.front]; this.front++; return item; }
peek() { return this.items[this.front]; }
size() { return this.rear - this.front; }}
// Ejemploconst queue = new Queue();queue.enqueue('Task 1');queue.enqueue('Task 2');console.log(queue.dequeue()); // 'Task 1'Lista enlazada
La lista enlazada es eficiente para insertar y eliminar elementos en medio de la lista. Implementamos una lista enlazada simple:
class Node { constructor(value) { this.value = value; this.next = null; }}
class LinkedList { constructor() { this.head = null; this.tail = null; this.length = 0; }
append(value) { const newNode = new Node(value); if (!this.head) { this.head = newNode; this.tail = newNode; } else { this.tail.next = newNode; this.tail = newNode; } this.length++; }
prepend(value) { const newNode = new Node(value); newNode.next = this.head; this.head = newNode; if (!this.tail) { this.tail = newNode; } this.length++; }
print() { const arr = []; let current = this.head; while (current) { arr.push(current.value); current = current.next; } return arr; }}
// Ejemploconst list = new LinkedList();list.append(10);list.append(20);list.prepend(5);console.log(list.print()); // [5, 10, 20]2. Algoritmos de búsqueda: lineal y binaria
La búsqueda es una de las operaciones más comunes. Consideremos dos enfoques: la búsqueda lineal simple y la búsqueda binaria eficiente.
Búsqueda lineal
Adecuada para datos no ordenados. Complejidad O(n):
function linearSearch(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { return i; // Devolvemos el índice } } return -1;}
console.log(linearSearch([3, 7, 1, 9, 4], 9)); // 3Búsqueda binaria
Requiere un array ordenado. Complejidad O(log n). Implementación en Node.js:
function binarySearch(arr, target) { let left = 0; let right = arr.length - 1;
while (left <= right) { const mid = M