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.
Колледж кітапханасында жұмыс істеп отырсыз Жайма шуақ бір күні әр түрлі тақырыптағы 1,280 кітап келеді. Кітаптар тізіліп тұр, бірақ шашыраңқы, олар ретімен тұрған жоқ, автоматты сұрыптау жүйесі жұмыс істемейді. Ертең сабақ басталатыны да жағдайды қиындатып тұр, бұл таңертең ең алдымен студенттер кітап іздеуге топырлап келеді деген сөз. Бәрін уақытында орнына қойып үлгересіз бе? Сұрыптауды кез келген қатардан бастау - ең тиімді әдістердің бірі. Егер кітаптар өз орнында тұрса, онда сол жерде қалдырыңыз. Басқа жағдайда орнын ауыстыру қажет. Келесі екінші және үшінші кітапқа қараңыз, сол әрекетті қайталаңыз, соңына жеткенше жалғастыра беріңіз. Бір кезде сіз соңында тұратын кітапты табасыз, яғни әр кітаптың орнын ауыстыруды жалғастыра беріңіз, соңғы нүктеге жеткенше ретімен жылжып отырыңыз. Содан кейін басынан бастап, соңғы кітапты тиісті орнына қою үшін әрекетті қайталаңыз, бәрі сұрыпталмайынша үдерісті жалғастыра беріңіз. Бұл тәсілдің атауы - Bubble Sort. Бұл оңай, бірақ көп уақыт алады. Бірінші кезеңде 1,279 кітапты салыстырасыз, содан кейін 1,278, т.с.с., соңында 818,560 салыстыруға тең болады. Егер әр әрекет бір секунд уақыт алса, жұмыс тоғыз күнге созылады. Екінші стратегия: тек алғашқы екі кітапты сұрыптаудан басталады. Сосын үшінші кітапты алып, келесі екінші кітаптың орнына қойыңыз. Егер оның екінші кітапқа қатысы болса, кітаптың орнын ауыстырыңыз, кейін, оны бірінші тұрған кітаппен салыстырыңыз, қажет болса, орнын ауыстырыңыз. Сіз алғашқы үш кітапты сұрыптадыңыз. Егер екінші кітаптан бұрын тұрса, кітаптың орнын ауыстырыңыз, жаңа кітапты алдыңғысымен салыстырып, ауыстыру керек, кітаптар дұрыс орналаспайынша сұрыптауды жалғастырыңыз. Бұл әдіс Insertion Sort деп аталады. Bubble Sort әдісінен айырмашылығы әр жұп кітапты салыстырудың қажеті жоқ. Орта есеппен алғанда әр кітапты оған дейін шыққан кітаптардың жартысымен салыстыру керек. Жалпы салыстыру саны 409,280 бұл жұмысқа бес күн керек. Сіз әлі де көп салыстыру жасайсыз. Бұл - табылған ақыл. Алдымен, кездейсоқ кітапты алыңыз. Бұны бір бөлім деп атап, оны әрбір екінші кітаппен салыстырыңыз. Содан кейін қатарды екіге бөліп, сол жақ бөлімнің алдында тұрған кітаптардың бәрін алып оң жаққа қойыңыз. Сіз біраз уақытты үнемдедіңіз сол жақтағы кітаптардың ешқайсысын оң жақтағы кітаптармен салыстырудың қажеті жоқ. Енді тек сол жақтағы кітаптарға қараңыз, сіз тағы да кез келген кітапты ала аласыз осыдан кейін кітаптарды қайта бөліңіз. Сіз осындай бөлімдерді құрастыра аласыз яғни, сізде шағын қатар болғанша, сұрыптаудың басқа стратегиясын пайдаланып, жылдам сұрыптайтын едіңіз. Сұрыптаудың әр кезегі шамамен 1,280 салыстыруды қажет етеді. Бөлімдер жеткілікті деңгейде теңестірілсе, кітаптарды он қатардан 128-ге бөлу керек, бұл шамамен жеті раунд болады, немесе 8,960 секунд. Бұл қатарды сұрыптауға әрқайсысына шамамен 22 секунд кетеді деген сөз. Жалпы алғанда бұл әдіс QuickSort атымен танымал, шамамен кітаптарды үш жарым сағатта сұрыптай аласыз. Бірақ бір нәрсе бар. Бөлінген кітаптар бір жақты болуы мүмкін, бұл уақытты мүлдем үнемдемейді. Мұндай жағдай сирек кездеседі. Сондықтан QuickSort сұрыптаудың ең жақсы әдісі болғандықтан, программистер қазіргі таңда қолданып жүр. Интернет-дүкендегі тауарлардың бағасын сұрыптау үшін пайдаланады. Осы жерле жақын жанармай бекеттерінің тізімін құрау үшін де пайдалы Сіздің мысалыңызда уақыт үнемдеп, сұрыптауды жылдам аяқтадыңыз Кітапханадағы тағы бір қарбалас күн аяқталды.