NAG Library Routine Document
M01NAF searches an ordered vector of real numbers and returns the index of the first value equal to the sought-after item.
||M1, M2, IFAIL
M01NAF is based on Professor Niklaus Wirth's implementation of the Binary Search algorithm (see Wirth (2004)
), but with two modifications. First, if the sought-after item is less than the value of the first element of the array to be searched,
is returned. Second, if a value equal to the sought-after item is not found, the index of the immediate lower value is returned.
Wirth N (2004) Algorithms and Data Structures 35–36 Prentice Hall
- 1: VALID – LOGICALInput
: if VALID
is set to .TRUE. parameter checking will be performed. If VALID
is set to .FALSE. M01NAF will be called without parameter checking (which includes checking that array RV
is sorted in ascending order) and the routine will return with
. See Section 8
for further details.
- 2: RV(M2) – REAL (KIND=nag_wp) arrayInput
: elements M1
contain real values to be searched.
must be sorted in ascending order.
- 3: M1 – INTEGERInput
: the index of the first element of RV
to be searched.
- 4: M2 – INTEGERInput
: the index of the last element of RV
to be searched.
- 5: ITEM – REAL (KIND=nag_wp)Input
On entry: the sought-after item.
- 6: IFAIL – INTEGERInput/Output
must be set to
. If you are unfamiliar with this parameter you should refer to Section 3.3
in the Essential Introduction for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value
is recommended. If the output of error messages is undesirable, then the value
is recommended. Otherwise, if you are not familiar with this parameter, the recommended value is
. When the value is used it is essential to test the value of IFAIL on exit.
unless the routine detects an error or a warning has been flagged (see Section 6
6 Error Indicators and Warnings
If on entry
, explanatory error messages are output on the current error message unit (as defined by X04AAF
Errors or warnings detected by the routine:
(Note: these errors will only be returned if .)
On entry, elements M1
are not sorted in ascending order.
On entry, .
On entry, .
The argument VALID
should be used with caution. Set it to .FALSE. only if you are confident that the other arguments are correct, in particular that array RV
is in fact arranged in ascending order. If you wish to search the same array RV
many times, you are recommended to set VALID
to .TRUE. on first call of M01NAF and to .FALSE. on subsequent calls, in order to minimize the amount of time spent checking RV
, which may be significant if RV
The time taken by M01NAF is , where , when .
This example reads a list of double precision numbers and sought-after items and performs the search for these items.
9.1 Program Text
Program Text (m01nafe.f90)
9.2 Program Data
Program Data (m01nafe.d)
9.3 Program Results
Program Results (m01nafe.r)