c8-5 (779528)

Файл №779528 c8-5 (Numerical Recipes in C)c8-5 (779528)2017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла

8.5 Selecting the Mth Largest341rank of the jth element of the original array of keys, ranging from 1 (if that elementwas the smallest) to N (if that element was the largest). One can easily constructa rank table from an index table, however:for (j=1;j<=n;j++) irank[indx[j]]=j;}Figure 8.4.1 summarizes the concepts discussed in this section.8.5 Selecting the Mth LargestSelection is sorting’s austere sister. (Say that five times quickly!) Where sortingdemands the rearrangement of an entire data array, selection politely asks for a singlereturned value: What is the kth smallest (or, equivalently, the m = N +1−kth largest)element out of N elements? The fastest methods for selection do, unfortunately,rearrange the array for their own computational purposes, typically putting all smallerelements to the left of the kth, all larger elements to the right, and scrambling theorder within each subset.

This side effect is at best innocuous, at worst downrightinconvenient. When the array is very long, so that making a scratch copy of it is taxingon memory, or when the computational burden of the selection is a negligible partof a larger calculation, one turns to selection algorithms without side effects, whichleave the original array undisturbed.

Such in place selection is slower than the fasterselection methods by a factor of about 10. We give routines of both types, below.The most common use of selection is in the statistical characterization of a setof data. One often wants to know the median element in an array, or the top andbottom quartile elements. When N is odd, the median is the kth element, withk = (N + 1)/2. When N is even, statistics books define the median as the arithmeticmean of the elements k = N/2 and k = N/2 + 1 (that is, N/2 from the bottomand N/2 from the top). If you accept such pedantry, you must perform two separateselections to find these elements.

For N > 100 we usually define k = N/2 to bethe median element, pedants be damned.The fastest general method for selection, allowing rearrangement, is partitioning, exactly as was done in the Quicksort algorithm (§8.2). Selecting a “random”partition element, one marches through the array, forcing smaller elements to theleft, larger elements to the right. As in Quicksort, it is important to optimize theinner loop, using “sentinels” (§8.2) to minimize the number of comparisons. Forsorting, one would then proceed to further partition both subsets. For selection,we can ignore one subset and attend only to the one that contains our desired kthelement.

Selection by partitioning thus does not need a stack of pending operations,and its operations count scales as N rather than as N log N (see [1]). Comparisonwith sort in §8.2 should make the following routine obvious: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).void rank(unsigned long n, unsigned long indx[], unsigned long irank[])Given indx[1..n] as output from the routine indexx, returns an array irank[1..n], thecorresponding table of ranks.{unsigned long j;342Chapter 8.Sorting#define SWAP(a,b) temp=(a);(a)=(b);(b)=temp;l=1;ir=n;for (;;) {if (ir <= l+1) {Active partition contains 1 or 2 elements.if (ir == l+1 && arr[ir] < arr[l]) {Case of 2 elements.SWAP(arr[l],arr[ir])}return arr[k];} else {mid=(l+ir) >> 1;Choose median of left, center, and right elSWAP(arr[mid],arr[l+1])ements as partitioning element a.

Alsoif (arr[l] > arr[ir]) {rearrange so that arr[l] ≤ arr[l+1],SWAP(arr[l],arr[ir])arr[ir] ≥ arr[l+1].}if (arr[l+1] > arr[ir]) {SWAP(arr[l+1],arr[ir])}if (arr[l] > arr[l+1]) {SWAP(arr[l],arr[l+1])}i=l+1;Initialize pointers for partitioning.j=ir;a=arr[l+1];Partitioning element.for (;;) {Beginning of innermost loop.do i++; while (arr[i] < a);Scan up to find element > a.do j--; while (arr[j] > a);Scan down to find element < a.if (j < i) break;Pointers crossed. Partitioning complete.SWAP(arr[i],arr[j])}End of innermost loop.arr[l+1]=arr[j];Insert partitioning element.arr[j]=a;if (j >= k) ir=j-1;Keep active the partition that contains theif (j <= k) l=i;kth element.}}}In-place, nondestructive, selection is conceptually simple, but it requires a lotof bookkeeping, and it is correspondingly slower.

The general idea is to pick somenumber M of elements at random, to sort them, and then to make a pass throughthe array counting how many elements fall in each of the M + 1 intervals definedby these elements. The kth largest will fall in one such interval — call it the “live”interval. One then does a second round, first picking M random elements in the liveinterval, and then determining which of the new, finer, M + 1 intervals all presentlylive elements fall into. And so on, until the kth element is finally localized within asingle array of size M , at which point direct selection is possible.How shall we pick M ? The number of rounds, logM N = log2 N/ log2 M ,will be smaller if M is larger; but the work to locate each element among M + 1subintervals will be larger, scaling as log2 M for bisection, say.

Each roundSample 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).float select(unsigned long k, unsigned long n, float arr[])Returns the kth smallest value in the array arr[1..n].

The input array will be rearrangedto have this value in location arr[k], with all smaller elements moved to arr[1..k-1] (inarbitrary order) and all larger elements in arr[k+1..n] (also in arbitrary order).{unsigned long i,ir,j,l,mid;float a,temp;3438.5 Selecting the Mth Largestrequires looking at all N elements, if only to find those that are still alive, whilethe bisections are dominated by the N that occur in the first round. MinimizingO(N logM N ) + O(N log2 M ) thus yields the resultM ∼2√log2 N(8.5.1)#include "nrutil.h"#define M 64#define BIG 1.0e30#define FREEALL free_vector(sel,1,M+2);free_lvector(isel,1,M+2);float selip(unsigned long k, unsigned long n, float arr[])Returns the kth smallest value in the array arr[1..n]. The input array is not altered.{void shell(unsigned long n, float a[]);unsigned long i,j,jl,jm,ju,kk,mm,nlo,nxtmm,*isel;float ahi,alo,sum,*sel;if (k < 1 || k > n || n <= 0) nrerror("bad input to selip");isel=lvector(1,M+2);sel=vector(1,M+2);kk=k;ahi=BIG;alo = -BIG;for (;;) {Main iteration loop, until desired elemm=nlo=0;ment is isolated.sum=0.0;nxtmm=M+1;for (i=1;i<=n;i++) {Make a pass through the whole array.if (arr[i] >= alo && arr[i] <= ahi) {Consider only elements in the current brackets.mm++;if (arr[i] == alo) nlo++;In case of ties for low bracket.Now use statistical procedure for selecting m in-range elements with equalprobability, even without knowing in advance how many there are!if (mm <= M) sel[mm]=arr[i];else if (mm == nxtmm) {nxtmm=mm+mm/M;sel[1 + ((i+mm+kk) % M)]=arr[i]; The % operation provides a some}what random number.sum += arr[i];}}if (kk <= nlo) {Desired element is tied for lower bound;FREEALLreturn it.return alo;}else if (mm <= M) {All in-range elements were kept.

So reshell(mm,sel);turn answer by direct method.ahi = sel[kk];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).The square root of the logarithm is so slowly varying that secondary considerations ofmachine timing become important. We use M = 64 as a convenient constant value.Two minor additional tricks in the following routine, selip, are (i) augmentingthe set of M random values by an M + 1st, the arithmetic mean, and (ii) choosingthe M random values “on the fly” in a pass through the data, by a method that makeslater values no less likely to be chosen than earlier ones.

(The underlying idea is togive element m > M an M/m chance of being brought into the set. You can proveby induction that this yields the desired result.)344Chapter 8.SortingFREEALLreturn ahi;}}Approximate timings: selip is about 10 times slower than select. Indeed,for N in the range of ∼ 105 , selip is about 1.5 times slower than a full sort withsort, while select is about 6 times faster than sort. You should weigh timeagainst memory and convenience carefully.Of course neither of the above routines should be used for the trivial cases offinding the largest, or smallest, element in an array. Those cases, you code by handas simple for loops. There are also good ways to code the case where k is modest incomparison to N , so that extra memory of order k is not burdensome.

Характеристики

Тип файла
PDF-файл
Размер
126,14 Kb
Материал
Тип материала
Высшее учебное заведение

Тип файла PDF

PDF-формат наиболее широко используется для просмотра любого типа файлов на любом устройстве. В него можно сохранить документ, таблицы, презентацию, текст, чертежи, вычисления, графики и всё остальное, что можно показать на экране любого устройства. Именно его лучше всего использовать для печати.

Например, если Вам нужно распечатать чертёж из автокада, Вы сохраните чертёж на флешку, но будет ли автокад в пункте печати? А если будет, то нужная версия с нужными библиотеками? Именно для этого и нужен формат PDF - в нём точно будет показано верно вне зависимости от того, в какой программе создали PDF-файл и есть ли нужная программа для его просмотра.

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7021
Авторов
на СтудИзбе
260
Средний доход
с одного платного файла
Обучение Подробнее