5.*7 External SortingSometimes data is so huge that it does not fit int dịch - 5.*7 External SortingSometimes data is so huge that it does not fit int Việt làm thế nào để nói

5.*7 External SortingSometimes data


5.*7 External Sorting
Sometimes data is so huge that it does not fit into internal memory. In this section we will learn how to sort such data sets in the external memory model introduced in Section 2.2. It distinguishes between a fast internal memory of size M and a large external memory. Data is moved in the memory hierarchy in blocks of size B. Scanning data is fast in external memory and mergesort is based on scanning. We therefore take mergesort as the starting point for external memory sorting. Assume the input is given as an array in external memory. We describe a nonre- cursive implementation for the case that the number of elements n is divisible by B. WeloadsubarraysofsizeM intointernalmemory,sortthemusingourfavoritealgo- rithm, e.g., qSort, and write the sorted subarrays back to external memory. We refer to the sorted subarrays as runs. The run formation phase takes n/B block reads and n/B blockwrites,i.e.,atotalof 2n/B I/Os.Thenwemergepairsofrunsintolarger runs in dlog(n/M)e merge phases ending up with a single sorted run. Figure 5.14 gives an example for n = 48 and runs of length twelve. How do we merge two runs? We keep one block from each of the two input runs and the output run in internal memory. We call these blocks buffers. Initially, the input buffers are filled with the first B elements of the input runs and the output buffer is empty. We compare the leading elements of the input buffers and move the smaller one to the output buffer. If an input buffer becomes empty, we fetch the next block of the corresponding input run, if the output buffer is full, we write it to external memory. Each merge phase reads all current runs and writes new runs of twice the length. Therefore each phase needs n/B block reads and n/B block writes. Summing over all phases, we obtain 2n/B(1 + dlogn/Me) I/Os. The technique works provided that M ≥ 3B.
120 5 Sorting and Selection
MultiwayMergesort
In general, internal memory can hold many blocks and not just three. We will de- scribe how to make full use of the available internal memory during merging. The idea is to merge more than just two runs; this will reduce the number of phases. In k-way merging, we merge k sorted sequences into a single output sequence. In each step we find the input sequence with the smallest first element. This element is removed and appended to the output sequence. External memory implementation is easy as long as we have enough internal memory for k input buffer blocks, one output buffer block, and a small amount of additional storage. For each sequence, we need to remember which element we are currently con- sidering. To find the smallest element among all k sequences, we keep their current elementsinapriorityqueue.Apriorityqueuemaintainsasetofelementssupporting the operations insertion and deletion of the minimum. Chapter 6 explains how prior- ityqueuescanbeimplementedsothatinsertionanddeletiontaketimeO(logk)fork elements.Thepriorityqueuetellsusineachstepwhichsequencecontainsthesmall- est element. We delete it from the priority queue, move it to the output buffer, and insertthenextelementfromthecorrespondinginputbufferintothepriorityqueue.If an input buffer runs dry, we fetch the next block of the corresponding sequence and if the output buffer becomes full, we write it to the external memory. How large can we choose k? We need to keep k + 1 blocks in internal memory and we need a priority queue for k keys. So we need (k + 1)B + O(k) ≤ M or k = O(M/B). The number of merging phases is reduced to dlogk(n/M)e and hence the total number of I/Os becomes
2
n B³1 +llogM/B n Mm´ . (5.1) The difference to binary merging is the much larger base of the logarithm. Interest- ingly, the above upper bound for the I/O-complexity of sorting isalso a lower bound [4],i.e.,underfairlygeneralassumptions,noexternalsortingalgorithmwithlessI/O operations is possible. Inpractice,thenumberofmergephaseswillbeverysmall.Observethatasingle merge phase suffices as long as n ≤ M2/B. We first form M/B runs of length M each and then merge these runs into a single sorted sequence. If internal memory stands for DRAMs and external memory stands for disks, this bound on n is no real restriction for all practical system configurations. Exercise101. Show that multiway mergesort needs only O(nlogn) element com- parisons. Exercise102 (Balanced systems). Study the current market prices of computers, internal memory, and mass storage (currently hard disks). Also estimate the block sizeneededtoachievegoodbandwidthforI/O.Canyoufindanyconfigurationwhere multi-waymergesortwouldrequiremorethanonemergingphaseforsortinganinput filling all the disks in the system? If so, which fraction of the system cost would you have to spend on additional internal memory to go back to a single merging phase?
5.7 * External Sorting 121
SampleSort The most popular internal memory sorting algorithm is not mergesort but quicksort. So it is natural to look for an external memory sorting algorithm based on quick- sort.WewillsketchSamplesort.Ithasthesameperformanceguaranteeasmultiway mergesort (Expression 5.1), however only in expectation and not worst case. It is is easier to adapt to parallel disks and parallel processors than merging-based al- gorithms. Furthermore, similar algorithms can be used for fast external sorting of integer keys along the lines of Section 5.6. Instead of the single pivot element of quicksort, we now use k − 1 splitter el-ements s1,..., sk−1 to split an input sequence into k output sequences or buckets. Bucket i gets the elements e with si−1 ≤ e < si. To simplify matters we define the artificial splitters s0 = −∞and sk = ∞and we assume that all elements have dif- ferentkeys.Thesplittersshouldbechoseninsuchawaythatthebucketshaveasize ofroughly n/k.Thebucketsarethensortedrecursively.Inparticular,bucketsthatfit into the internal memory can subsequently be sorted internally. Note the similarity to MSB-radix sort in Section 5.6. The main challenge is to find good splitters quickly. Sample sort uses a fast and simple randomized strategy. For some integer a, we randomly choose ak + k − 1 sampleelementsfromtheinput.ThesampleS isthensortedinternallyandwedefine the splitters as si = S[(a + 1)i] for 1 ≤ i ≤ k − 1, i.e., subsequent splitters are separatedbyasamples,thefirstsplitterisprecededbyasamples,andthelastsplitter isfollowedbyasamples.Takinga = 0resultsinasmallsampleset,butsplittingwill not be very good. Moving all elements to the sample will result in perfect splitters, but the sample is too big. The analysis shows that setting a = O(logk) achieves roughly equal bucket sizes at low cost for sampling and sorting the sample. The most I/O-intensive part of sample sort is k-way distribution of the input sequence to the buckets. We keep one buffer block for the input sequence and one buffer block for each bucket. These buffers are handled analogously to the buffer blocks in k-way merging. If the splitters are kept in a sorted array, we can find the right bucket for an input element e in timeO(logk) using binary search. Theorem21. Sample sort sorts n inputs using O³n B³1 +llogM/B n Mm´´ expected I/O steps. Internal work isO(nlogn). We leave the detailed proof to the reader and explain only the key ingredient of the analysis. We use k = Θ(min(n/M,M/B)) buckets and a sample of size O(klogk).Thefollowinglemmashowsthatwiththissamplesize,itisunlikelythat any bucket has size much larger than average. We hide the constant factors behind O(•)-notation because our analysis is not very tight in this respect. Lemma16. Let k ≥ 2 and a + 1 = 12lnk. A sample of size (a + 1)k −1 suffices to ensure that no bucket receives more than 4n/k elements with probability at least 1/2.
122 5 Sorting and Selection
Proof. As in our analysis of quicksort (Theorem 18), it is useful to study the sorted version s0 = he0 1,...,e0niof the input. Assume there is a bucket with at least 4n/kelements assigned to it. We estimate the probability of this event. We split s0 into k/2 segments of length 2n/k. The j-th segment tj contains elementse0 2jn/k+1 toe02(j+1)n/k.If4n/k elementsendupinsomebuckettheremust be some segment tj such that all its elements end up in the same bucket. This can only happen if less than a + 1 samples are taken from tj because otherwise at least one splitter would be chosen from tj and its elements would not end up in a single bucket. Let us concentrate on a fixed j. WeuserandomvariableX todenotethenumberofsamplestakenfromtj.Recall that we take (a + 1)k −1 samples. For each sample i, 1 ≤ i ≤ (a + 1)k −1, we define an indicator variable Xi with Xi = 1 if the i-th sample is taken from tj and Xi = 0 otherwise. Then X =P1≤i≤(a+1)k−1 Xi. Also, the Xi’s are independent and prob(Xi = 1) = 2/k. Independence allows us to use the so-called Chernoff bound(A.5)toestimatetheprobabilitythatX < a+1.WehaveE[X] = ((a+1)k− 1)•2 k = 2(a+1)−2/k ≥ 3(a+1)/2.HenceX < a+1impliesX < (1−1/3)E[X]and so we can use (A.5) with ² = 1/3. Thus prob(X < a + 1) ≤ e−(1/9)E[X]/2 ≤ e−(a+1)/12 = e−lnk = 1 k . The probability that an insufficient number of samples is chosen from a fixed tj is thus at most 1/k and hence the probability that an insufficient number is chosen fromsome tj isatmost(k/2)•(1/k) = 1/2.Thuswithprobabilityatleast 1/2,each bucket receives less than 4n/k elements. Exercise103. WorkoutthedetailsofanexternalmemoryimplementationofSample sort. In particular, explain how to implement multi-way distribution using 2n/B + k + 1 I/O steps if the internal memory is large enough to store k + 1 blocks of data andO(k) additional elements. Exercise104 (Many equal keys). Explain how to generalize multiway distribution sothatitstillworksifsomekeysoccur very often.Hint:thereareatleasttwodiffer- ent solutions. One uses the sample to find out which elements are frequent. Another solution makes all elements unique by interpreting an element e at input position i as the pair (e,i). *Exercise105(Moreaccura
0/5000
Từ: -
Sang: -
Kết quả (Việt) 1: [Sao chép]
Sao chép!

5.*7 phân loại bên ngoài
đôi khi dữ liệu là rất lớn như vậy mà nó không không fit vào bộ nhớ. Trong phần này, chúng tôi sẽ tìm hiểu làm thế nào để sắp xếp các bộ dữ liệu trong mô hình bộ nhớ ngoài giới thiệu trong phần 2.2. Nó phân biệt giữa một bộ nhớ nhanh trong kích thước M và một bộ nhớ ngoài lớn. Dữ liệu được di chuyển trong hệ thống phân cấp bộ nhớ trong khối lượng sinh Quét dữ liệu nhanh ở bên ngoài bộ nhớ và mergesort dựa trên quét. Chúng tôi do đó có mergesort như là điểm khởi đầu cho bộ nhớ ngoài phân loại. Giả sử các đầu vào được đưa ra như là một mảng trong bộ nhớ ngoài. Chúng tôi mô tả một thực hiện nonre-cursive cho trường hợp số lượng các yếu tố n là số chia hết cho sinh WeloadsubarraysofsizeM intointernalmemory, sortthemusingourfavoritealgo-rithm, Ví dụ:, qSort, và ghi được sắp xếp subarrays quay lại bộ nhớ ngoài. Chúng tôi đề cập đến subarrays được sắp xếp như chạy. Giai đoạn hình thành chạy mất n/B khối lần đọc và n/B blockwrites,i.e.,atotalof 2n/B I/Os.Thenwemergepairsofrunsintolarger chạy trong dlog(n/M) e kết hợp giai đoạn kết thúc với một đĩa đơn được sắp xếp chạy. Con số 5.14 cho một ví dụ cho n = 48 và chạy của chiều dài mười hai. Làm thế nào để chúng tôi có thể hợp nhất hai chạy? Chúng tôi giữ một khối từ mỗi của hai chạy đầu vào và đầu ra chạy trong bộ nhớ. Chúng tôi gọi các bộ đệm khối. Ban đầu, bộ đệm đầu vào là filled với các yếu tố chính B của chạy đầu vào và sản lượng đệm là sản phẩm nào. Chúng tôi so sánh các yếu tố hàng đầu của bộ đệm đầu vào và di chuyển một nhỏ hơn để các bộ đệm đầu ra. Nếu một bộ đệm đầu vào trở nên trống rỗng, chúng tôi lấy khối tiếp theo của đầu vào tương ứng chạy, nếu các bộ đệm đầu ra là đầy đủ, chúng tôi ghi nó vào bộ nhớ ngoài. Mỗi giai đoạn hợp nhất đọc tất cả hiện tại chạy và viết mới tập hai lần chiều dài. Do đó mỗi giai đoạn cần n/B khối lần đọc và viết n/B khối. Tổng hợp trên tất cả các giai đoạn, chúng tôi có được 2n/B(1 dlogn/Me) I/Os. Các công trình kỹ thuật cung cấp rằng M ≥ 3B.
120 5 phân loại và lựa chọn
MultiwayMergesort
nói chung, bộ nhớ có thể chứa nhiều khối và không chỉ là ba. Chúng tôi sẽ de-scribe làm thế nào để sử dụng đầy đủ bộ nhớ có sẵn trong thời gian qua việc sáp nhập. Mục đích là để hợp nhất nhiều hơn là chỉ hai chạy; Điều này sẽ làm giảm số lượng các giai đoạn. Trong k-cách sáp nhập, chúng tôi kết hợp trình tự k được sắp xếp thành một đầu ra duy nhất. Trong mỗi bước chúng tôi nhiều chuỗi đầu vào với các yếu tố chính nhỏ nhất. Nguyên tố này loại bỏ và thêm vào chuỗi sản lượng. Bộ nhớ ngoài thực hiện là dễ dàng miễn là chúng tôi có đủ bộ nhớ cho k bộ đệm đầu vào khối, một đầu ra bộ đệm khối, và một lượng nhỏ lưu trữ bổ sung. Cho mỗi chuỗi, chúng ta cần phải nhớ yếu tố mà chúng tôi đang hiện con-sidering. Để nhiều phần tử nhỏ nhất trong số tất cả k trình tự, chúng tôi giữ elementsinapriorityqueue hiện tại của họ.Apriorityqueuemaintainsasetofelementssupporting hoạt động chèn và xoá tối thiểu. Chương 6 giải thích như thế nào trước khi-ityqueuescanbeimplementedsothatinsertionanddeletiontaketimeO (logk) ngã ba yếu tố.Thepriorityqueuetellsusineachstepwhichsequencecontainsthesmall-est nguyên tố. Chúng tôi xóa nó từ hàng đợi ưu tiên, di chuyển nó vào bộ đệm đầu ra, và insertthenextelementfromthecorrespondinginputbufferintothepriorityqueue.Nếu một bộ đệm đầu vào chạy khô, chúng tôi lấy khối tiếp theo của dãy tương ứng và nếu bộ đệm đầu ra trở nên đầy đủ, chúng tôi viết nó vào bộ nhớ bên ngoài. Lớn như thế nào chúng tôi có thể chọn k? Chúng ta cần phải giữ cho k 1 khối trong bộ nhớ và chúng tôi cần một ưu tiên hàng đợi cho k phím. Vì vậy, chúng ta cần (k 1) B O(k) ≤ M hoặc k = O(M/B). Số lượng kết hợp giai đoạn giảm xuống còn dlogk(n/M) e và do đó trở thành tổng số I/Os
2
n B³1 llogM/B n Mm´. (5.1) sự khác biệt để sáp nhập nhị phân là cơ sở lớn hơn nhiều của logarit. Lãi suất-ingly, phía trên ở trên hướng đến sự I/O-phức tạp của isalso phân loại một ràng buộc thấp hơn [4],i.e.,underfairlygeneralassumptions,noexternalsortingalgorithmwithlessI/O hoạt động có thể. Inpractice, thenumberofmergephaseswillbeverysmall.Observethatasingle kết hợp giai đoạn suffices miễn là n ≤ M2/sinh Chúng tôi chính tạo thành M/B tập dài M mỗi và sau đó hợp nhất các chạy vào một chuỗi duy nhất được sắp xếp. Nếu bộ nhớ là viết tắt của DRAMs, và bộ nhớ ngoài là viết tắt của đĩa này bị ràng buộc vào n là không hạn chế thực tế cho tất cả các hệ thống thực tế configurations. Exercise101. Hiển thị rằng mergesort multiway cần chỉ O(nlogn) yếu tố com-parisons. Exercise102 (cân bằng hệ thống). Nghiên cứu giá cả thị trường hiện tại của máy tính, bộ nhớ, và khối lượng lưu trữ (hiện nay là đĩa cứng). Cũng ước tính khối sizeneededtoachievegoodbandwidthforI/O.Canyoufindanyconfigurationwhere multi-waymergesortwouldrequiremorethanonemergingphaseforsortinganinput filling tất cả các đĩa trong hệ thống? Nếu vì vậy, phần của hệ thống chi phí nào bạn có thể chi ngày bổ sung bộ nhớ nội bộ để trở lại một pha merging?
9.2 * bên ngoài phân loại 121
SampleSort thuật toán phân loại phổ biến nhất bộ nhớ không phải là mergesort nhưng hay Hoaresort. Vì vậy, nó là tự nhiên để tìm một bộ nhớ ngoài phân loại các thuật toán dựa trên nhanh chóng-loại.WewillsketchSamplesort.Ithasthesameperformanceguaranteeasmultiway mergesort (biểu hiện 5.1), Tuy nhiên chỉ trong kỳ vọng và không tồi tệ nhất trường hợp. Nó là dễ dàng hơn để thích ứng với song song đĩa và bộ vi xử lý song song hơn qua việc hợp nhất dựa trên al-gorithms. Hơn nữa, tương tự như thuật toán có thể được sử dụng để phân loại nhanh bên ngoài của các phím số nguyên dọc theo dòng của phần 5,6. Thay vì các yếu tố duy nhất trục hay Hoaresort, chúng tôi bây giờ sử dụng k − 1 splitter el-ements s1,..., sk−1 để tách một chuỗi đầu vào vào k đầu ra trình tự hoặc Xô. Xô tôi được yếu tố e với si−1 ≤ e < si. Để đơn giản hóa vấn đề chúng tôi define artificial splitter s0 = −∞and sk = ∞and chúng tôi giả định rằng tất cả các yếu tố có c-ferentkeys.Thesplittersshouldbechoseninsuchawaythatthebucketshaveasize ofroughly n/k.Thebucketsarethensortedrecursively.Inparticular,bucketsthatfit vào bộ nhớ nội bộ sau đó có thể được sắp xếp trong nội bộ. Lưu ý sự tương tự với MSB-sau loại trong phần 5,6. Thách thức chính là nhiều tốt splitter một cách nhanh chóng. Mẫu loại sử dụng một chiến lược ngẫu nhiên nhanh chóng và đơn giản. Với một số số nguyên a, chúng tôi ngẫu nhiên chọn ak k − 1 sampleelementsfromtheinput.ThesampleS isthensortedinternallyandwedefine splitter là si = S [(a 1) tôi] với 1 ≤ tôi ≤ k − 1, nghĩa là, sau đó splitter là separatedbyasamples,thefirstsplitterisprecededbyasamples, andthelastsplitter isfollowedbyasamples.Takinga = 0resultsinasmallsampleset, butsplittingwill không rất tốt. Di chuyển tất cả các yếu tố để mẫu sẽ dẫn đến hoàn hảo splitter, nhưng mẫu là quá lớn. Các phân tích cho thấy rằng thiết lập một = O(logk) đạt được kích thước đương Xô với chi phí thấp cho lấy mẫu và phân loại mẫu. Phần đặt I/O-tăng cường của mẫu loại là k-cách phân phối các chuỗi đầu vào để các Xô. Chúng tôi giữ cho đệm một khối dành cho chuỗi đầu vào và một bộ đệm khối cho mỗi nhóm. Các bộ đệm được xử lý cũng để khối bộ đệm trong k-cách hợp nhất. Nếu các Splitter được lưu giữ trong một mảng được sắp xếp, chúng tôi có thể nhiều thùng đúng cho một yếu tố đầu vào e timeO(logk) bằng cách sử dụng tìm kiếm nhị phân. Theorem21. Mẫu phân loại các loại đầu vào n bằng cách sử dụng O³n B³1 llogM/B n Mm´´ I/O mong đợi. Công việc nội bộ isO(nlogn). Chúng tôi rời khỏi chứng minh chi tiết để đọc và giải thích chỉ là thành phần quan trọng của việc phân tích. Chúng tôi sử dụng k = Θ(min(n/M,M/B)) Xô và một mẫu kích thước O(klogk).Thefollowinglemmashowsthatwiththissamplesize, itisunlikelythat bất kỳ Xô có kích thước lớn hơn nhiều hơn mức trung bình. Chúng tôi ẩn các yếu tố liên tục phía sau O (•)-ký hiệu vì phân tích của chúng tôi không phải là rất chặt chẽ trong sự tôn trọng này. Lemma16. Hãy để k ≥ 2 và 1 = 12lnk. Một mẫu kích thước (một 1) k −1 suffices để đảm bảo rằng không có xô nhận được nhiều hơn 4n/k yếu tố với xác suất tối thiểu 1/2.
122 5 phân loại và lựa chọn
bằng chứng. Như trong phân tích của chúng tôi hay Hoaresort (định lý 18), nó là hữu ích để nghiên cứu được sắp xếp Phiên bản s0 = he0 1,..., e0niof các đầu vào. Giả sử có một xô với ít 4n/kelements được giao. Chúng tôi ước tính xác suất của sự kiện này. Chúng tôi chia s0 vào k/2 phân đoạn của chiều dài 2n/k. J-th phân khúc tj chứa elementse0 2jn/k 1 toe02(j 1) n/k.If4n/k elementsendupinsomebuckettheremust là một số tj phân khúc như vậy mà tất cả các yếu tố của nó sẽ chỉ trong thùng cùng. Điều này chỉ có thể xảy ra nếu ít hơn một mẫu 1 được lấy từ tj bởi vì nếu không ít nhất một splitter sẽ được lựa chọn từ tj và các yếu tố không sẽ kết thúc trong một xô duy nhất. Hãy cho chúng tôi tập trung vào một fixed j. WeuserandomvariableX todenotethenumberofsamplestakenfromtj.Nhớ lại rằng chúng tôi có (1) k −1 mẫu. Cho mỗi mẫu i, 1 ≤ tôi ≤ (1) k −1, chúng tôi define một chỉ số biến Xi Xi = 1 nếu mẫu i-th được lấy từ tj và Xi = 0 nếu không. Sau đó X = P1≤i≤(a 1) k−1 Xi. Ngoài ra, của Xi được độc lập và prob(Xi = 1) = 2/k. độc lập cho phép chúng tôi sử dụng cái gọi là Chernoff ràng buộc (A.5) toestimatetheprobabilitythatX < một 1.WehaveE [X] = ((a 1) k− 1) •2 k = 2(a 1) −2/k ≥ 3 (1)/2.HenceX một < 1impliesX một < (1−1/3) E [X] và do đó, chúng tôi có thể sử dụng (A.5) với ² = 1/3. Do đó prob (X < một 1) ≤ e−(1/9) E [X] / 2 ≤ e−(a 1)/12 = e−lnk = 1 k. Xác suất mà một số insufficient mẫu được chọn từ một tức fixed là như vậy tối đa là 1/k và do đó khả năng rằng một số insufficient được chọn fromsome tj isatmost(k/2)•(1/k) = 1/2.Thuswithprobabilityatleast 1/2, mỗi nhóm sẽ nhận được ít hơn 4n/k yếu tố. Exercise103. WorkoutthedetailsofanexternalmemoryimplementationofSample loại. Đặc biệt, giải thích làm thế nào để thực hiện nhiều cách phân phối sử dụng 2n/B k 1 I/O bước nếu bộ nhớ là đủ lớn để lưu trữ k 1 khối dữ liệu andO(k) thành phần bổ sung. Exercise104 (nhiều người bằng phím). Giải thích làm thế nào để khái quát multiway phân phối sothatitstillworksifsomekeysoccur rất thường xuyên.Gợi ý: thereareatleasttwodiffer - ent giải pháp. Một sử dụng mẫu để nhiều ra yếu tố được thường xuyên. Một giải pháp làm cho tất cả các yếu tố duy nhất của giải thích một e phần tử lúc đầu vào vị trí tôi như các cặp (e, tôi). * Exercise105 (Moreaccura
đang được dịch, vui lòng đợi..
Kết quả (Việt) 2:[Sao chép]
Sao chép!

5.*7 External Sorting
Sometimes data is so huge that it does not fit into internal memory. In this section we will learn how to sort such data sets in the external memory model introduced in Section 2.2. It distinguishes between a fast internal memory of size M and a large external memory. Data is moved in the memory hierarchy in blocks of size B. Scanning data is fast in external memory and mergesort is based on scanning. We therefore take mergesort as the starting point for external memory sorting. Assume the input is given as an array in external memory. We describe a nonre- cursive implementation for the case that the number of elements n is divisible by B. WeloadsubarraysofsizeM intointernalmemory,sortthemusingourfavoritealgo- rithm, e.g., qSort, and write the sorted subarrays back to external memory. We refer to the sorted subarrays as runs. The run formation phase takes n/B block reads and n/B blockwrites,i.e.,atotalof 2n/B I/Os.Thenwemergepairsofrunsintolarger runs in dlog(n/M)e merge phases ending up with a single sorted run. Figure 5.14 gives an example for n = 48 and runs of length twelve. How do we merge two runs? We keep one block from each of the two input runs and the output run in internal memory. We call these blocks buffers. Initially, the input buffers are filled with the first B elements of the input runs and the output buffer is empty. We compare the leading elements of the input buffers and move the smaller one to the output buffer. If an input buffer becomes empty, we fetch the next block of the corresponding input run, if the output buffer is full, we write it to external memory. Each merge phase reads all current runs and writes new runs of twice the length. Therefore each phase needs n/B block reads and n/B block writes. Summing over all phases, we obtain 2n/B(1 + dlogn/Me) I/Os. The technique works provided that M ≥ 3B.
120 5 Sorting and Selection
MultiwayMergesort
In general, internal memory can hold many blocks and not just three. We will de- scribe how to make full use of the available internal memory during merging. The idea is to merge more than just two runs; this will reduce the number of phases. In k-way merging, we merge k sorted sequences into a single output sequence. In each step we find the input sequence with the smallest first element. This element is removed and appended to the output sequence. External memory implementation is easy as long as we have enough internal memory for k input buffer blocks, one output buffer block, and a small amount of additional storage. For each sequence, we need to remember which element we are currently con- sidering. To find the smallest element among all k sequences, we keep their current elementsinapriorityqueue.Apriorityqueuemaintainsasetofelementssupporting the operations insertion and deletion of the minimum. Chapter 6 explains how prior- ityqueuescanbeimplementedsothatinsertionanddeletiontaketimeO(logk)fork elements.Thepriorityqueuetellsusineachstepwhichsequencecontainsthesmall- est element. We delete it from the priority queue, move it to the output buffer, and insertthenextelementfromthecorrespondinginputbufferintothepriorityqueue.If an input buffer runs dry, we fetch the next block of the corresponding sequence and if the output buffer becomes full, we write it to the external memory. How large can we choose k? We need to keep k + 1 blocks in internal memory and we need a priority queue for k keys. So we need (k + 1)B + O(k) ≤ M or k = O(M/B). The number of merging phases is reduced to dlogk(n/M)e and hence the total number of I/Os becomes
2
n B³1 +llogM/B n Mm´ . (5.1) The difference to binary merging is the much larger base of the logarithm. Interest- ingly, the above upper bound for the I/O-complexity of sorting isalso a lower bound [4],i.e.,underfairlygeneralassumptions,noexternalsortingalgorithmwithlessI/O operations is possible. Inpractice,thenumberofmergephaseswillbeverysmall.Observethatasingle merge phase suffices as long as n ≤ M2/B. We first form M/B runs of length M each and then merge these runs into a single sorted sequence. If internal memory stands for DRAMs and external memory stands for disks, this bound on n is no real restriction for all practical system configurations. Exercise101. Show that multiway mergesort needs only O(nlogn) element com- parisons. Exercise102 (Balanced systems). Study the current market prices of computers, internal memory, and mass storage (currently hard disks). Also estimate the block sizeneededtoachievegoodbandwidthforI/O.Canyoufindanyconfigurationwhere multi-waymergesortwouldrequiremorethanonemergingphaseforsortinganinput filling all the disks in the system? If so, which fraction of the system cost would you have to spend on additional internal memory to go back to a single merging phase?
5.7 * External Sorting 121
SampleSort The most popular internal memory sorting algorithm is not mergesort but quicksort. So it is natural to look for an external memory sorting algorithm based on quick- sort.WewillsketchSamplesort.Ithasthesameperformanceguaranteeasmultiway mergesort (Expression 5.1), however only in expectation and not worst case. It is is easier to adapt to parallel disks and parallel processors than merging-based al- gorithms. Furthermore, similar algorithms can be used for fast external sorting of integer keys along the lines of Section 5.6. Instead of the single pivot element of quicksort, we now use k − 1 splitter el-ements s1,..., sk−1 to split an input sequence into k output sequences or buckets. Bucket i gets the elements e with si−1 ≤ e < si. To simplify matters we define the artificial splitters s0 = −∞and sk = ∞and we assume that all elements have dif- ferentkeys.Thesplittersshouldbechoseninsuchawaythatthebucketshaveasize ofroughly n/k.Thebucketsarethensortedrecursively.Inparticular,bucketsthatfit into the internal memory can subsequently be sorted internally. Note the similarity to MSB-radix sort in Section 5.6. The main challenge is to find good splitters quickly. Sample sort uses a fast and simple randomized strategy. For some integer a, we randomly choose ak + k − 1 sampleelementsfromtheinput.ThesampleS isthensortedinternallyandwedefine the splitters as si = S[(a + 1)i] for 1 ≤ i ≤ k − 1, i.e., subsequent splitters are separatedbyasamples,thefirstsplitterisprecededbyasamples,andthelastsplitter isfollowedbyasamples.Takinga = 0resultsinasmallsampleset,butsplittingwill not be very good. Moving all elements to the sample will result in perfect splitters, but the sample is too big. The analysis shows that setting a = O(logk) achieves roughly equal bucket sizes at low cost for sampling and sorting the sample. The most I/O-intensive part of sample sort is k-way distribution of the input sequence to the buckets. We keep one buffer block for the input sequence and one buffer block for each bucket. These buffers are handled analogously to the buffer blocks in k-way merging. If the splitters are kept in a sorted array, we can find the right bucket for an input element e in timeO(logk) using binary search. Theorem21. Sample sort sorts n inputs using O³n B³1 +llogM/B n Mm´´ expected I/O steps. Internal work isO(nlogn). We leave the detailed proof to the reader and explain only the key ingredient of the analysis. We use k = Θ(min(n/M,M/B)) buckets and a sample of size O(klogk).Thefollowinglemmashowsthatwiththissamplesize,itisunlikelythat any bucket has size much larger than average. We hide the constant factors behind O(•)-notation because our analysis is not very tight in this respect. Lemma16. Let k ≥ 2 and a + 1 = 12lnk. A sample of size (a + 1)k −1 suffices to ensure that no bucket receives more than 4n/k elements with probability at least 1/2.
122 5 Sorting and Selection
Proof. As in our analysis of quicksort (Theorem 18), it is useful to study the sorted version s0 = he0 1,...,e0niof the input. Assume there is a bucket with at least 4n/kelements assigned to it. We estimate the probability of this event. We split s0 into k/2 segments of length 2n/k. The j-th segment tj contains elementse0 2jn/k+1 toe02(j+1)n/k.If4n/k elementsendupinsomebuckettheremust be some segment tj such that all its elements end up in the same bucket. This can only happen if less than a + 1 samples are taken from tj because otherwise at least one splitter would be chosen from tj and its elements would not end up in a single bucket. Let us concentrate on a fixed j. WeuserandomvariableX todenotethenumberofsamplestakenfromtj.Recall that we take (a + 1)k −1 samples. For each sample i, 1 ≤ i ≤ (a + 1)k −1, we define an indicator variable Xi with Xi = 1 if the i-th sample is taken from tj and Xi = 0 otherwise. Then X =P1≤i≤(a+1)k−1 Xi. Also, the Xi’s are independent and prob(Xi = 1) = 2/k. Independence allows us to use the so-called Chernoff bound(A.5)toestimatetheprobabilitythatX < a+1.WehaveE[X] = ((a+1)k− 1)•2 k = 2(a+1)−2/k ≥ 3(a+1)/2.HenceX < a+1impliesX < (1−1/3)E[X]and so we can use (A.5) with ² = 1/3. Thus prob(X < a + 1) ≤ e−(1/9)E[X]/2 ≤ e−(a+1)/12 = e−lnk = 1 k . The probability that an insufficient number of samples is chosen from a fixed tj is thus at most 1/k and hence the probability that an insufficient number is chosen fromsome tj isatmost(k/2)•(1/k) = 1/2.Thuswithprobabilityatleast 1/2,each bucket receives less than 4n/k elements. Exercise103. WorkoutthedetailsofanexternalmemoryimplementationofSample sort. In particular, explain how to implement multi-way distribution using 2n/B + k + 1 I/O steps if the internal memory is large enough to store k + 1 blocks of data andO(k) additional elements. Exercise104 (Many equal keys). Explain how to generalize multiway distribution sothatitstillworksifsomekeysoccur very often.Hint:thereareatleasttwodiffer- ent solutions. One uses the sample to find out which elements are frequent. Another solution makes all elements unique by interpreting an element e at input position i as the pair (e,i). *Exercise105(Moreaccura
đang được dịch, vui lòng đợi..
 
Các ngôn ngữ khác
Hỗ trợ công cụ dịch thuật: Albania, Amharic, Anh, Armenia, Azerbaijan, Ba Lan, Ba Tư, Bantu, Basque, Belarus, Bengal, Bosnia, Bulgaria, Bồ Đào Nha, Catalan, Cebuano, Chichewa, Corsi, Creole (Haiti), Croatia, Do Thái, Estonia, Filipino, Frisia, Gael Scotland, Galicia, George, Gujarat, Hausa, Hawaii, Hindi, Hmong, Hungary, Hy Lạp, Hà Lan, Hà Lan (Nam Phi), Hàn, Iceland, Igbo, Ireland, Java, Kannada, Kazakh, Khmer, Kinyarwanda, Klingon, Kurd, Kyrgyz, Latinh, Latvia, Litva, Luxembourg, Lào, Macedonia, Malagasy, Malayalam, Malta, Maori, Marathi, Myanmar, Mã Lai, Mông Cổ, Na Uy, Nepal, Nga, Nhật, Odia (Oriya), Pashto, Pháp, Phát hiện ngôn ngữ, Phần Lan, Punjab, Quốc tế ngữ, Rumani, Samoa, Serbia, Sesotho, Shona, Sindhi, Sinhala, Slovak, Slovenia, Somali, Sunda, Swahili, Séc, Tajik, Tamil, Tatar, Telugu, Thái, Thổ Nhĩ Kỳ, Thụy Điển, Tiếng Indonesia, Tiếng Ý, Trung, Trung (Phồn thể), Turkmen, Tây Ban Nha, Ukraina, Urdu, Uyghur, Uzbek, Việt, Xứ Wales, Yiddish, Yoruba, Zulu, Đan Mạch, Đức, Ả Rập, dịch ngôn ngữ.

Copyright ©2025 I Love Translation. All reserved.

E-mail: