Sorting Algorithms
Study of the pure logic behind classic sorting algorithms in Python.
Key Concepts
- Fundamentals of sorting algorithms
- Variable swapping and list partitioning
- Basic time complexity
- HTML5
<canvas>setup and rendering - Object-Oriented Programming in JavaScript (
class) - Animation loops using
requestAnimationFrame
Part 1: Sorting Algorithms (Python)
We will focus on the pure logic of three classic algorithms. The code uses yield to facilitate future integration with step-by-step visualizers.
1. Bubble Sort
Compares adjacent elements and swaps them if they are in the wrong order. Larger elements "bubble" to the end of the list.
def bubble_sort(datos):
n = len(datos)
for i in range(n - 1):
for j in range(n - i - 1):
if datos[j] > datos[j + 1]:
datos[j], datos[j + 1] = datos[j + 1], datos[j]
2. Insertion Sort
Builds the sorted array one element at a time, taking an element from the unsorted part and inserting it into its correct position within the sorted part.
def insertion_sort(datos):
n = len(datos)
for i in range(1, n):
clave = datos[i]
j = i - 1
while j >= 0 and clave < datos[j]:
datos[j + 1] = datos[j]
j -= 1
datos[j + 1] = clave
3. Quick Sort
Uses the "divide and conquer" strategy. It picks a pivot, partitions the list into elements smaller and larger than the pivot, and recursively sorts the sublists.
def quick_sort(datos):
yield from _quick_sort_recursivo(datos, 0, len(datos) - 1)
def _quick_sort_recursivo(datos, inicio, fin):
if inicio < fin:
indice_pivote = yield from particion(datos, inicio, fin)
yield from _quick_sort_recursivo(datos, inicio, indice_pivote - 1)
yield from _quick_sort_recursivo(datos, indice_pivote + 1, fin)
def particion(datos, inicio, fin):
pivote = datos[fin]
borde = inicio
for j in range(inicio, fin):
if datos[j] < pivote:
datos[borde], datos[j] = datos[j], datos[borde]
borde += 1
datos[borde], datos[fin] = datos[fin], datos[borde]
return borde
Part 2: Particle Physics Engine (JavaScript)
This second part is developed independently on the frontend. We will use the HTML5 <canvas> to render particles that bounce off edges and flee from the mouse.
1. Canvas Setup and Events
We set the canvas to occupy the full screen and track the mouse position.
const canvas = document.getElementById('lienzo');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particulas = [];
const colorNeon = '0, 255, 204';
let raton = { x: null, y: null, radio: 150 };
window.addEventListener('mousemove', (e) => { raton.x = e.x; raton.y = e.y; });
window.addEventListener('mouseout', () => { raton.x = null; raton.y = null; });
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
2. Particle Class
Defines the physical properties (position, velocity, size) and the methods to update the physics and draw the particle.
class Particula {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 2 + 0.5;
this.velX = (Math.random() - 0.5) * 1.5;
this.velY = (Math.random() - 0.5) * 1.5;
}
actualizar() {
// Basic movement
this.x += this.velX;
this.y += this.velY;
// Wall bouncing
if (this.x > canvas.width || this.x < 0) this.velX *= -1;
if (this.y > canvas.height || this.y < 0) this.velY *= -1;
// Mouse interaction
if (raton.x != null) {
let dx = raton.x - this.x;
let dy = raton.y - this.y;
let distancia = Math.sqrt(dx * dx + dy * dy);
if (distancia < raton.radio && distancia > 0) {
const fuerza = (raton.radio - distancia) / raton.radio;
this.x -= (dx / distancia) * fuerza * 4;
this.y -= (dy / distancia) * fuerza * 4;
}
}
}
dibujar() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgb(${colorNeon})`;
ctx.fill();
}
}
3. Animation Loop
We create the particle ecosystem and generate a continuous loop that clears the canvas, updates physics, and draws connection lines based on proximity.
// Instantiate particles
for (let i = 0; i < 150; i++) particulas.push(new Particula());
function animar() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particulas.length; i++) {
particulas[i].actualizar();
particulas[i].dibujar();
// Draw connection lines between close particles
for (let j = i + 1; j < particulas.length; j++) {
let dx = particulas[i].x - particulas[j].x;
let dy = particulas[i].y - particulas[j].y;
let distancia = Math.sqrt(dx * dx + dy * dy);
if (distancia < 100) {
ctx.beginPath();
ctx.strokeStyle = `rgba(${colorNeon}, ${1 - distancia / 100})`;
ctx.lineWidth = 0.6;
ctx.moveTo(particulas[i].x, particulas[i].y);
ctx.lineTo(particulas[j].x, particulas[j].y);
ctx.stroke();
}
}
}
requestAnimationFrame(animar);
}
animar();