Ordenamiento
Introducido
7:45
Estructuras de datos y algoritmos
This course is about choosing a container by what it costs. The first unit is the yardstick: how cost grows with the size of the input. The next four are the…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| Insertion sort/ɪnˈsɜːʃn sɔːt/ | A sorting method that inserts each new item into its correct position in the already sorted part of a list. |
| inversion/ɪnˈvɜːʃn/ | inversión |
| Merge sort/mɜːdʒ sɔːt/ | a sort that splits the list in half, sorts each half and merges the two sorted halves |
| Quicksort/ˈkwɪksɔːt/ | a sort that partitions the list around a pivot and then sorts each side the same way |
| lower bound/ˈləʊə baʊnd/ | A value less than or equal to every value in a set or permitted range. |
| Counting sort/ˈkaʊntɪŋ sɔːt/ | A non-comparison sort that counts how often each key value occurs and writes the values out in order, in O(n + k) time. |
| stable/ˈsteɪbl/ | Describing a sort that keeps records with equal keys in their original order. |
El conjunto de datos del curso
- Ordenar $[5, 2, 9, 1, 7, 3]$. Ordenamiento por inserción crece un prefijo ordenado, desplazando cada nueva tarjeta hacia atrás; ordenamiento por fusión divide por la mitad, ordena cada mitad y fusiona; quicksort particiona alrededor de una pivote; ordenamiento burbuja intercambia inversiones adyacentes — educativo, raramente usado.


Esta tarjeta se corrigió, por eso aparece en inglés hasta que se actualice su traducción.
Inversions measure the disorder
- An inversion 逆序 is a pair of items in the wrong order. Our list has 8: $(5,2), (5,1), (5,3), (2,1), (9,1), (9,7), (9,3), (7,3)$.
- Swapping two neighbours that are out of order fixes exactly one inversion. So insertion sort implemented with adjacent swaps, and any sort that swaps only out-of-order neighbours (such as bubble sort), needs exactly 8 swaps here.
- A reversed list of $n$ items has $n(n-1)/2$ inversions, so these sorts are $O(n^2)$: fine for a short or nearly sorted list, slow for a long one.
A sort that swaps only adjacent out-of-order pairs makes, on a dataset, exactly — swaps
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Each swap of neighbours fixes exactly one inversion, so the number of swaps equals the number of inversions.
The dataset [5, 2, 9, 1, 7, 3] has — inversions
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Count the out-of-order pairs: (5,2), (5,1), (5,3), (2,1), (9,1), (9,7), (9,3), (7,3).
Ambos a mano
- Inserción: $2$ desplaza uno; $9$ ninguno; $1$ tres; $7$ uno; $3$ tres — total $8$ desplazamientos, $11$ comparaciones, resultado $[1, 2, 3, 5, 7, 9]$.
- Fusión: reducir a la mitad en $[5, 2, 9]$ y $[1, 7, 3]$; recursivamente $[2, 5, 9]$ y $[1, 3, 7]$; fusionar una vez: $1, 2, 3, 5, 7, 9$ con $10$ comparaciones. En $n = 1000$ las familias se dividen por $100$.
Una entrada ordenada con pivote del primer elemento es el peor caso de quicksort, $O(n^2)$ — no una rareza sino una trampa. La estabilidad sobrevive en fusión e inserción, no en quick ni heap.

Merge sort on the same dataset uses — comparisons
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Measured: 10 comparisons against insertion 11 — and the gap widens with size.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Quicksort: partition around a pivot
- Quicksort 快速排序 picks a pivot, moves smaller items to its left and larger ones to its right, then sorts each side the same way. With the last item 3 as pivot, $[5, 2, 9, 1, 7, 3]$ becomes $[2, 1, 3, 5, 7, 9]$: 3 is now at index 2, its final place.
- If each pivot splits the list roughly in half, quicksort takes $O(n \log n)$ on average and needs no extra array.
- But if the pivot is always the smallest or largest item (for example, the first item of an already sorted list), each step removes only one item: $O(n^2)$. Real libraries choose the pivot at random or as a median of three.
Partition $[4, 8, 1, 6, 5]$ around the last element $5$. Where does $5$ land?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Two elements (4 and 1) are smaller than 5, so the pivot takes index 2.
Esta tarjeta se corrigió, por eso aparece en inglés hasta que se actualice su traducción.
The lower bound for comparison sorts
- A sort that only compares items must tell apart all $n!$ possible orders. Each yes/no comparison can at best halve the possibilities, so the worst case needs at least $\lceil \log_2 n! \rceil$ comparisons.
- For $n = 6$: $6! = 720$ and $\log_2 720 \approx 9.5$, so at least 10 comparisons are needed in the worst case. The example above uses 10 comparisons on that particular input. In general $\log_2 n! \approx n \log_2 n$, so this lower bound 下界 is $\Theta(n \log n)$.
What is the minimum worst-case number of comparisons to sort 5 items?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
5! = 120 and log2 120 is about 6.9, so at least 7 comparisons.
A cleverer comparison sort could sort every list of $6$ distinct items with at most $9$ comparisons.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
$6! = 720$ orders, and $9$ yes/no comparisons can tell apart at most $2^9 = 512$ of them. The worst case needs at least $\lceil \log_2 720 \rceil = 10$ comparisons, whatever the algorithm.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Beating the bound without comparing
- The bound is only for sorts that compare. Counting sort 计数排序 counts how often each key value appears, then writes the values out in order: $O(n + k)$ for keys from 0 to $k$.
- 1,000 exam marks from 0 to 100 take about $1{,}000 + 101 = 1{,}101$ steps, against $1{,}000 \times \log_2 1{,}000 \approx 9{,}966$ comparisons. Radix sort repeats counting sort digit by digit for larger keys.
Counting sort of 1,000 keys with values 0 to 100: about how many steps ($n + k + 1$)?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$1{,}000 + 101 = 1{,}101$.
No sorting algorithm can beat $O(n \log n)$.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Only comparison sorts are bound; counting sort is $O(n + k)$.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Worked example: why stability matters
- Records already sorted by name: (Al, A), (Bo, B), (Cy, B), (Di, A). Now sort them by grade with a stable 稳定的 sort, which keeps items with equal keys in their old order.
- Result: (Al, A), (Di, A), (Bo, B), (Cy, B). Within each grade the names are still in alphabetical order, so the list is now sorted by grade, then name.
- An unstable sort may put (Di, A) before (Al, A). Merge sort and insertion sort are stable; the usual quicksort and heapsort are not.
Sort (Al, A), (Bo, B), (Cy, B), (Di, A) by grade with a stable sort. The second record is:
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Equal grades keep their name order: Al, Di, Bo, Cy.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Marks that slip away
- Calling quicksort always $O(n \log n)$. A bad pivot, such as the first item of a sorted list, gives $\Theta(n^2)$.
- Assuming every sort is stable. Heapsort and the usual quicksort 快速排序 can reorder equal keys.
- Hoping to beat $n \log n$ by comparing. Six items need at least 10 comparisons in the worst case; only sorts that do not compare escape the bound.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Recap
- Insertion sort 插入排序: one move per inversion, $O(n^2)$, good for small or nearly sorted lists.
- Merge sort: $O(n \log n)$ and stable; quicksort: $O(n \log n)$ on average, $O(n^2)$ with bad pivots.
- Comparison sorts need at least $\lceil \log_2 n! \rceil$ comparisons; counting sort avoids comparing.
¿Qué salió mal? Solo el equipo del sitio ve esta información.