You work at the college library. You're in the middle of a quiet afternoon when suddenly a shipment of 1,280 different books arrives. The books have been dropped of in one long straight line, but they're all out of order, and the automatic sorting system is broken. To make matters worse, classes start tomorrow, which means that first thing in the morning, students will show up in droves looking for these books. How can you get them all sorted in time? One way would be to start at one end of the line with the first pair of books. If the first two books are in order, then leave them as they are. Otherwise, swap them. Then, look at the second and third books, repeat the process, and continue until you reach the end of the line. At some point, you'll come across the book that should be last, and keep swapping it with every subsequent book, moving it down the line until it reaches the end where it belongs. Then, start from the beginning and repeat the process to get the second to last book in its proper place, and keep going until all books are sorted. This approach is called Bubble Sort. It's simple but slow. You'd make 1,279 comparisons in the first round, then 1,278, and so on, adding up to 818,560 comparisons. If each took just one second, the process would take over nine days. A second strategy would be to start by sorting just the first two books. Then, take the third book and compare it with the book in the second spot. If it belongs before the second book, swap them, then compare it with the book in the first spot, and swap again if needed. Now you've sorted the first three books. Keep adding one book at a time to the sorted sub-line, comparing and swapping the new book with the one before it until it's correctly placed among the books sorted so far. This is called Insertion Sort. Unlike Bubble Sort, it usually doesn't require comparing every pair of books. On average, we'd expect to only need to compare each book to half of the books that came before it. In that case, the total number of comparisons would be 409,280, taking almost five days. You're still doing way too many comparisons. Here's a better idea. First, pick a random book. Call it the partition and compare it to every other book. Then, divide the line by placing all the books that come before the partition on its left and all the ones that come after it on its right. You've just saved loads of time by not having to compare any of the books on the left to any of the ones on the right ever again. Now, looking only at the books on the left, you can again pick a random partition book and separate those books that come before it from those that come after it. You can keep creating sub-partitions like this until you have a bunch of small sub-lines, each of which you'd sort quickly using another strategy, like Insertion Sort. Each round of partitioning requires about 1,280 comparisons. If your partitions are pretty balanced, dividing the books into 128 sub-lines of ten would take about seven rounds, or 8,960 seconds. Sorting these sub-lines would add about 22 seconds each. All in all, this method known as QuickSort could sort the books in under three and a half hours. But there's a catch. Your partitions could end up lopsided, saving no time at all. Luckily, this rarely happens. That's why QuickSort is one of the most efficient strategies used by programmers today. They use it for things like sorting items in an online store by price, or creating a list of all the gas stations close to a given location sorted by distance. In your case, you're done quick sorting with time to spare. Just another high-stakes day in the library.
Trabajas en la biblioteca de la universidad. En mitad de una tarde tranquila te llegan de repente unos 1280 libros, entregados en línea recta pero desordenados y el sistema de clasificación automática no funciona. Además, mañana comienzan las clases de nuevo, lo que significa que a primera hora de la mañana todos los estudiantes se presentarán en la biblioteca buscando sus libros. ¿Cómo se pueden ordenar todos los libros a tiempo? Una forma sería comenzar por el primer par de libros en un extremo de la fila y si los dos primeros están en orden, dejarlos como están. De lo contrario, intercambiarlos. Hacer lo mismo con el segundo y el tercero, repetir el procedimiento y seguir hasta llegar al final de la fila. En un momento dado, se encuentra el libro que debe ser el último, se sigue intercambiándolo con los libros posteriores desplazándolo a lo largo de la fila hasta que llegue al final. Volver a empezar desde el principio y repetir el mismo procedimiento para colocar el segundo en el lugar que le corresponde; seguir hasta ordenar todos los libros. Este proceso se llama el método de la burbuja. Es simple pero lento. En la primera ronda se llegan a hacer 1279 comparaciones, luego 1278 y y así sucesivamente, hasta llegar a un total de 818 560. Si cada comparación dura un segundo, harían falta nueve días. Una segunda técnica implica empezar con solo los primeros 2 libros para luego comparar el tercer libro con el que se encuentra en el segundo lugar. Si le corresponde colocarlo delante de este segundo libro, intercambiarlos, luego compararlos con el primero en el primer lugar y volver a intercambiarlos si hace falta. Ya se han ordenado los primeros tres. Seguir con un libro a la vez, ordenándolos por conjuntos, comparando cada uno de ellos e intercambiando con el de delante hasta encontrar el lugar que le corresponde entre los ya ordenados. Esto se denomina la técnica por inserción. A diferencia del método de la burbuja, no requiere comparar cada par. En promedio, creemos que solo es necesario comparar cada libro con la mitad de todos los libros que le preceden. En este caso el número total de comparaciones será 409 280 y tardaría cinco días. Aun así, hay que comparar demasiados libros. Te proponemos una idea mejor. Elegir un libro al azar. Usarlo de separador y luego compararlo con todos los otros libros. Luego, dividir la línea y colocar todos los libros de antes de la separación a la izquierda y los otros a la derecha. Acabas de ahorrarte un montón de tiempo y sin tener que comparar todos los libros de la izquierda con todos que tiene a la derecha. Ahora, al fijarte solo en los de la izquierda vuelve a elegir uno al azar y separa los libros de delante y detrás de ese en dos grupos. Sigue dividiendo los libros en base al mismo principio hasta que llegues a tener pequeñas pilas de libros, listas para ordenarlas en base al método de inserción. Cada ciclo requiere unas 1280 comparaciones. Si creaste pilas parecidas deberías tener 128 pilas, con 10 libros en cada grupo, tardando 8960 segundos. Añade 22 segundos para ordenar estos subconjuntos. Con esta técnica llamada catalogación rápida puedes llegar a ordenar tus libros en menos de una hora y media. Pero tiene trampa. Si los subconjuntos están desproporcionados perderás mucho tiempo pero afortunadamente, esto ocurre muy de vez en cuando. Esta técnica es una de las más eficientes usada en la actualidad por los programadores informáticos por ejemplo en las tiendas en línea para categorizar elementos, según el precio o crear una lista de todas las gasolineras más cercanas a un lugar determinado, en base a la distancia. En este caso, la catalogación está resuelta y queda tiempo de sobra. Y aquí va otro día crucial en la biblioteca.