c8-1 (779524)
Текст из файла
330Chapter 8.SortingCITED REFERENCES AND FURTHER READING:Knuth, D.E. 1973, Sorting and Searching, vol. 3 of The Art of Computer Programming (Reading,MA: Addison-Wesley). [1]Sedgewick, R. 1988, Algorithms, 2nd ed. (Reading, MA: Addison-Wesley), Chapters 8–13. [2]8.1 Straight Insertion and Shell’s MethodStraight insertion is an N 2 routine, and should be used only for small N ,say < 20.The technique is exactly the one used by experienced card players to sort theircards: Pick out the second card and put it in order with respect to the first; then pickout the third card and insert it into the sequence among the first two; and so on untilthe last card has been picked out and inserted.void piksrt(int n, float arr[])Sorts an array arr[1..n] into ascending numerical order, by straight insertion. n is input; arris replaced on output by its sorted rearrangement.{int i,j;float a;for (j=2;j<=n;j++) {a=arr[j];i=j-1;while (i > 0 && arr[i] > a) {arr[i+1]=arr[i];i--;}arr[i+1]=a;}Pick out each element in turn.Look for the place to insert it.Insert it.}What if you also want to rearrange an array brr at the same time as you sortarr? Simply move an element of brr whenever you move an element of arr:Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).For small N one does better to use an algorithm whose operation count goesas a higher, i.e., poorer, power of N , if the constant in front is small enough.
ForN < 20, roughly, the method of straight insertion (§8.1) is concise and fast enough.We include it with some trepidation: It is an N 2 algorithm, whose potential formisuse (by using it for too large an N ) is great. The resultant waste of computertime is so awesome, that we were tempted not to include any N 2 routine at all. Wewill draw the line, however, at the inefficient N 2 algorithm, beloved of elementarycomputer science texts, called bubble sort. If you know what bubble sort is, wipe itfrom your mind; if you don’t know, make a point of never finding out!For N < 50, roughly, Shell’s method (§8.1), only slightly more complicated toprogram than straight insertion, is competitive with the more complicated Quicksorton many machines.
This method goes as N 3/2 in the worst case, but is usually faster.See references [1,2] for further information on the subject of sorting, and fordetailed references to the literature.8.1 Straight Insertion and Shell’s Method331void piksr2(int n, float arr[], float brr[])Sorts an array arr[1..n] into ascending numerical order, by straight insertion, while makingthe corresponding rearrangement of the array brr[1..n].{int i,j;float a,b;Pick out each element in turn.Look for the place to insert it.Insert it.}For the case of rearranging a larger number of arrays by sorting on one ofthem, see §8.4.Shell’s MethodThis is actually a variant on straight insertion, but a very powerful variant indeed.The rough idea, e.g., for the case of sorting 16 numbers n1 .
. . n16 , is this: First sort,by straight insertion, each of the 8 groups of 2 (n1 , n9 ), (n2 , n10), . . . , (n8 , n16).Next, sort each of the 4 groups of 4 (n1 , n5 , n9 , n13 ), . . . , (n4 , n8 , n12 , n16). Nextsort the 2 groups of 8 records, beginning with (n1 , n3 , n5 , n7 , n9 , n11, n13 , n15).Finally, sort the whole list of 16 numbers.Of course, only the last sort is necessary for putting the numbers into order. Sowhat is the purpose of the previous partial sorts? The answer is that the previoussorts allow numbers efficiently to filter up or down to positions close to their finalresting places. Therefore, the straight insertion passes on the final sort rarely have togo past more than a “few” elements before finding the right place.
(Think of sortinga hand of cards that are already almost in order.)The spacings between the numbers sorted on each pass through the data (8,4,2,1in the above example) are called the increments, and a Shell sort is sometimescalled a diminishing increment sort. There has been a lot of research into how tochoose a good set of increments, but the optimum choice is not known. The set.
. . , 8, 4, 2, 1 is in fact not a good choice, especially for N a power of 2. A muchbetter choice is the sequence(3k − 1)/2, . . . , 40, 13, 4, 1(8.1.1)which can be generated by the recurrencei1 = 1,ik+1 = 3ik + 1,k = 1, 2, . . .(8.1.2)It can be shown (see [1]) that for this sequence of increments the number of operationsrequired in all is of order N 3/2 for the worst possible ordering of the original data.Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).for (j=2;j<=n;j++) {a=arr[j];b=brr[j];i=j-1;while (i > 0 && arr[i] > a) {arr[i+1]=arr[i];brr[i+1]=brr[i];i--;}arr[i+1]=a;brr[i+1]=b;}332Chapter 8.SortingFor “randomly” ordered data, the operations count goes approximately as N 1.25, atleast for N < 60000. For N > 50, however, Quicksort is generally faster. Theprogram follows:CITED REFERENCES AND FURTHER READING:Knuth, D.E.
1973, Sorting and Searching, vol. 3 of The Art of Computer Programming (Reading,MA: Addison-Wesley), §5.2.1. [1]Sedgewick, R. 1988, Algorithms, 2nd ed. (Reading, MA: Addison-Wesley), Chapter 8.8.2 QuicksortQuicksort is, on most machines, on average, for large N , the fastest knownsorting algorithm. It is a “partition-exchange” sorting method: A “partitioningelement” a is selected from the array. Then by pairwise exchanges of elements, theoriginal array is partitioned into two subarrays. At the end of a round of partitioning,the element a is in its final place in the array. All elements in the left subarray are≤ a, while all elements in the right subarray are ≥ a.
The process is then repeatedon the left and right subarrays independently, and so on.The partitioning process is carried out by selecting some element, say theleftmost, as the partitioning element a. Scan a pointer up the array until you findan element > a, and then scan another pointer down from the end of the arrayuntil you find an element < a. These two elements are clearly out of place for thefinal partitioned array, so exchange them.
Continue this process until the pointerscross. This is the right place to insert a, and that round of partitioning is done. TheSample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).void shell(unsigned long n, float a[])Sorts an array a[1..n] into ascending numerical order by Shell’s method (diminishing incrementsort). n is input; a is replaced on output by its sorted rearrangement.{unsigned long i,j,inc;float v;inc=1;Determine the starting increment.do {inc *= 3;inc++;} while (inc <= n);do {Loop over the partial sorts.inc /= 3;for (i=inc+1;i<=n;i++) {Outer loop of straight insertion.v=a[i];j=i;while (a[j-inc] > v) {Inner loop of straight insertion.a[j]=a[j-inc];j -= inc;if (j <= inc) break;}a[j]=v;}} while (inc > 1);}.
Характеристики
Тип файла PDF
PDF-формат наиболее широко используется для просмотра любого типа файлов на любом устройстве. В него можно сохранить документ, таблицы, презентацию, текст, чертежи, вычисления, графики и всё остальное, что можно показать на экране любого устройства. Именно его лучше всего использовать для печати.
Например, если Вам нужно распечатать чертёж из автокада, Вы сохраните чертёж на флешку, но будет ли автокад в пункте печати? А если будет, то нужная версия с нужными библиотеками? Именно для этого и нужен формат PDF - в нём точно будет показано верно вне зависимости от того, в какой программе создали PDF-файл и есть ли нужная программа для его просмотра.















