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.
Та их сургуулийнхаа номын санд ажилладаг. Нэгэн нам гүн үд өнгөрч байтал гэнэт 1280 өөр өөр номны ачаа ирлээ. Эдгээр номнууд бүгдээрээ нэг урт цуваанд орж буугдсан ч ямар ч дараалалд ороогүй, мөн автомат ангилагч систем эвдэрчээ. Хамгийн хэцүү нь хичээл маргааш эхэлнэ. Үүнээс болж өглөө эрт оюутнууд номнуудаа хайсаар ирнэ. Та яаж бүгдийг нь амжиж ангилах вэ? Нэг үзүүрийн эхний 2 номноос эхэлж болох юм. Хэрэв эхний 2 ном нь зөв байрлалд байвал байгаагаар нь орхи. Үгүй бол байрыг нь соль. Дараа нь 2 болон 3 дахь номнуудад өмнөх үйлдлийг үйлдлээ дахин давтсаар эгнээний төгсгөлд очтлоо үргэлжлүүл. Хэзээ нэгэн цагт, хамгийн сүүлд орох ном гарч ирэхээр түүний дараа байгаа бүх номнуудтай сольсоор байх ёстой хамгийн сүүлийн байранд ирнэ. Дараа нь, эх дээр нь очоод хийсэн үйлдлээ дахин давтсаар хамгийн сүүлээсээ хоёрт орох номыг зөв байранд нь оруулаад бүх ном дараалалд ортол нь давтана. Энэхүү аргыг "Хөөсөн ангилалт" гэдэг. Энэ нь амархан боловч их цаг шаарддаг. Хамгийн эхэнд 1279 харьцуулалт хийгдэнэ. Дараа нь 1278 гэсээр нийт 818,560 харьцуулалт хийгдэнэ. Хэрэв харьцуулалт тус бүрт нэг сэкунд зарцуулвал, нийт 9 өдөр үргэлжлэнэ. 2 дахь арга нь эхний 2 номыг ангилж эхэлнэ. Үүний дараа 3 дахь номыг 2 дахь номтой харьцуулна. Хэрэв 3 дугаар нь 2 дахь номныхоо өмнө байх хэрэгтэй бол байрыг нь соль. Үүний дараа 1-р байранд байгаа номтой харьцуулаад солих шаардлагатай бол байрыг нь солино. Одоо эхний 3 ном ангилагдчихлаа. Ангилагдсан хэсэг дээр нэг ном нэмж, шинэ нэмсэн номоо урд нь байгаатай харьцуулсаар ангилагдсан номнуудын дунд зөв байранд нь оруулна. Үүнийг "Нэмэгдэх ангилалт" гэж нэрлэнэ. "Хөөсөн ангилалт" - аас ялгаатай нь 2 ном болгоныг харьцуулах шаардлагагүй. Дунджаар нэг номыг урд нь байгаа нийт номнуудын хагастай нь л харьцуулна. Иймд нийт хийх харьцуулалт нь 409280 болж ойролцоогоор 5 өдөр шаардана. Дэндүү олон харьцуулалт хийгдсэн хэвээр л байна. Илүү дээр санаа байна. Эхлээд дурын номоо сонго. Үүнийгээ "Хуваагч" гэж нэрлээд бусад бүх номнуудтай харьцуул. Дараа нь цувааг "Хуваагч" - ийн өмнө орох бүх номнуудыг зүүн талд нь гарган дараа нь орохыг баруун талд нь гарга. Сая маш их цагийг зүүн талд байгаа номнуудыг баруун талд байгаатай харьцуулах шаардлагагүй болж хэмнэлээ. Одоо зөвхөн зүүн талд байгаа номнууд дундаас Дахин нэг өөр "Хуваагч" ном сонгон аван өмнө нь орох ёстойг хойно нь байхаас салгана. Дахин "Дэд хуваагч" үүсгэсээр жижиг жижиг цуваануудтай болоод "Нэмэгдэх ангилал" мэтийг ашиглан хурдан ангилна. Хуваагдалт болгон 1280 харьцуулалт хийгдэнэ. Хэрэв чиний хуваалтууд тэгш хэмтэй бол нийт номоо 10 аар хуваасан 128 жижиг цуваа болгоход 7 үе шаардна эсвэл 8960 сэкунд. Жижиг цуваануудыг ангилах нь тус тус 22 сэкунд шаардна. Энэхүү "Хурдан ангилалт" нь бүх номыг 3 цаг хагаст ангилж дуусгана. Гэхдээ алдаж болно. Хуваагдалтууд нь буруу болж цаг хэмнээгүй ч болж болно. Азаар энэ маш ховорхон тохиолддог. Ийм учраас "Хурдан ангилалт" нь хамгийн ашигтай аргуудын нэг бөгөөд програм бичих үндсэн алгоритмуудын нэг болсон. Үүнийг онлайн дэлгүүрийн барааг үнийн дараалалд оруулах эсвэл ойрхон байгаа шатахуун түгээх станцуудыг зайгаар нь ангилах зэрэгт өргөнөөр ашигладаг. Харин та номоо маш хурдан ангилаад дуусгачихлаа. Номын санчийн бас нэгэн завгүй өдөр.