Quicksort
Picks a pivot, splits smaller from larger values and sorts each side recursively.
- Level
- Advanced
- Topic:
- Sorting & searching
- Concepts:
- Input & output
- Arrays
- SubProcesos
- Functions
- Recursion
- Repetir
- Si
- Randomness
Run, change and debug this example in your browser.
What you'll learn
Particionar uses Hoare's method: two indexes walk in from both ends and swap whenever each one finds a value on the wrong side of the pivot. Then each part is sorted with the same idea. If the pivot splits the array roughly in half it costs O(n log n); if it always lands at one end, O(n²). It needs no extra array, only the call stack (O(log n)).
Code
// Muestra el arreglo completo solo si es corto (30 o menos)SubProceso MostrarDatos(titulo, datos, n) Definir i Como Entero Si n <= 30 Entonces Escribir Sin Saltar titulo Para i <- 1 Hasta n Hacer Escribir Sin Saltar datos[i], " " FinPara Escribir "" SiNo Escribir titulo, n, " números (el primero es ", datos[1], " y el último ", datos[n], ")" FinSiFinSubProceso// Partición de Hoare: deja a la izquierda los valores <= pivote y a la derecha// los >= pivote, y devuelve dónde termina la parte izquierda.Funcion corte <- Particionar(datos, izquierda, derecha) Definir corte, pivote, i, j, aux Como Entero // Usamos el elemento del medio como pivote pivote <- datos[Trunc((izquierda + derecha) / 2)] i <- izquierda - 1 j <- derecha + 1 Repetir // i avanza hasta encontrar uno que no debería estar a la izquierda Repetir i <- i + 1 Hasta Que datos[i] >= pivote // j retrocede hasta encontrar uno que no debería estar a la derecha Repetir j <- j - 1 Hasta Que datos[j] <= pivote // Si no se cruzaron, los intercambiamos y seguimos Si i < j Entonces aux <- datos[i] datos[i] <- datos[j] datos[j] <- aux FinSi Hasta Que i >= j corte <- jFinFuncionSubProceso OrdenarRapido(datos, izquierda, derecha) Definir corte Como Entero Si izquierda < derecha Entonces corte <- Particionar(datos, izquierda, derecha) // Cada lado se ordena por separado, con la misma idea OrdenarRapido(datos, izquierda, corte) OrdenarRapido(datos, corte + 1, derecha) FinSiFinSubProcesoAlgoritmo Quicksort Definir datos, n, i Como Entero Escribir "¿Cuántos números quieres ordenar? (1 a 512)" Leer n Dimension datos[n] Para i <- 1 Hasta n Hacer datos[i] <- Aleatorio(1, 99) FinPara MostrarDatos("Antes: ", datos, n) OrdenarRapido(datos, 1, n) MostrarDatos("Después: ", datos, n)FinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
¿Cuántos números quieres ordenar? (1 a 512)User answer: 12Antes: 57 95 53 48 81 13 78 10 53 4 56 3 Después: 3 4 10 13 48 53 53 56 57 78 81 95
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n²) |
| Memory | O(log n) |
Traits:Not stableIn place
Challenge
Use a random element of the range as the pivot instead of the middle one.
Show hint
Aleatorio(izquierda, derecha) gives a position in the range; store datos[that position] in pivote.
Related examples
Linear vs. Binary Search
Counts the comparisons each search needs on the same sorted list.
IntermediateShell Sort
Insertion sort between far-apart elements, with a gap that shrinks every pass.
AdvancedBubble Sort
Sorts random numbers by swapping neighbors, and stops as soon as they're in order.
Intermediate