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.
Você trabalha na biblioteca da faculdade. Bem no meio de uma tarde tranquila, de repente, chega um carregamento com 1.280 livros diferentes. Os livros foram deixados numa linha reta, mas estão todos fora da ordem, e o sistema de seleção automática está quebrado. Para piorar as coisas, as aulas começam amanhã, o que significa que logo de manhã cedinho vai aparecer um monte de estudantes procurando por esses livros. Como você vai conseguir organizá-los a tempo? Um jeito seria começar numa extremidade da linha, com os dois primeiros livros. Se os dois primeiros livros estiverem na ordem, então deixe-os onde estão. Caso contrário, troque-os entre si. Depois, olhe o segundo e o terceiro livro, repita o processo, e continue até chegar ao final da linha. A uma certa altura, você vai chegar ao livro que deveria ser o último. Continue trocando-o de lugar com os livros subsequentes, passando-o de livro em livro até chegar ao fim da linha, onde é o lugar dele. A seguir, comece do início e repita todo o processo para colocar do segundo ao penúltimo livro nos lugares certos, e continue até que todos os livros estejam organizados. Essa abordagem se chama "método da bolha". É simples, porém lento. Você teria de fazer 1.279 comparações na primeira rodada, depois, 1.278, e assim por diante, chegando a 818.560 comparações. Se cada uma levar apenas um segundo, o processo todo levará mais de nove dias. Uma segunda estratégia seria começar ordenando apenas os dois primeiros livros. Depois, pegar o terceiro e comparar com o livro na segunda posição. Se ele estiver na frente do segundo livro, então troque os dois, depois compare-o com o livro na primeira posição, e troque de novo, se necessário. Agora que ordenou os primeiros três livros, continue a adicionar um livro de cada vez ao subconjunto ordenado, comparando e trocando o novo livro com o que estiver antes dele, até estar corretamente colocado entre os livros ordenados até então. Isso se chama "ordenação por inserção". Diferente do método bolha, ele em geral não exige que se compare cada par. Em média, espera-se ser necessário comparar cada livro somente com a metade dos livros que vieram antes dele. Nesse caso, o número total de comparações seria de 409.280, o que levaria quase 5 dias. Você ainda teria comparações demais a fazer. Eis aqui uma ideia melhor. Primeiro, pegue um livro qualquer. Chame-o de "a divisória" e compare-o com todos os outros livros. Depois, divida a linha, colocando todos os livros que vêm antes da divisória à esquerda desta, e todos aqueles que vêm depois dela, à sua direita. Você acabou de economizar um tempão ao não ter de comparar nenhum dos livros da esquerda com nenhum dos livros da direita. Bem, olhando agora apenas os livros da esquerda, você pode, de novo, eleger um "livro divisória" qualquer e separar os livros que vêm antes dele daqueles que vêm depois. Continue a criar subdivisões assim até ter um monte de subconjuntos, que você ordenará rapidamente usando outra estratégia: ordenação por inserção. Cada rodada de divisão dessa requer cerca de 1.280 comparações. Se suas divisões forem bem equilibradas, dividir os livros em 128 subconjuntos de 10 levaria cerca de 7 rodadas, ou 8.960 segundos. Ordenar esses subconjuntos adicionaria cerca de 22 segundos para cada um. No final das contas, esse método, conhecido como Quicksort, poderia ordenar livros em menos de três a quatro horas. Mas tem um porém. Se as divisões ficarem desproporcionais, não haverá nenhuma economia de tempo. Felizmente, isso raramente acontece. E essa é a razão por que o Quicksort é uma das estratégias mais eficientes usadas por programadores hoje em dia. Eles a usam para coisas como ordenar itens por preço numa loja on-line, ou criar uma lista dos postos de gasolina perto de um determinado lugar, de acordo com a distância. No seu caso, você terminou o "quick sorting" com tempo de sobra. E lá se vai mais um dia eletrizante na biblioteca.