CFLib.org – Common Function Library Project

arrayFindSorted(array, value)

Last updated September 30, 2005
Download UDF

author

Kenneth Fricklas                                  Kenneth Fricklas

Version: 1 | Requires: ColdFusion 5 | Library: DataManipulationLib

 
Rated 2 time(s). Average Rating: 3.0

Description:
Locate a value in an already-sorted array. Case-insensitive for strings. Code is useful since converting to a list would require finding a unique delimiter.

Return Values:
Returns the position of the match, or 0.

Example:

<CFSET a1 = ListToArray("1,2,4,5,10,12")>
<CFOUTPUT>
#arrayFindSorted(a1, "10")# <!--- displays 5 --->
</CFOUTPUT>

Parameters:

Name Description Required
array The array to check. Yes
value The value to look for. Yes

Full UDF Source:

<cfscript>
/**
* Locate a value in an already-sorted array.
*
* @param array      The array to check. (Required)
* @param value      The value to look for. (Required)
* @return Returns the position of the match, or 0.
* @author Kenneth Fricklas (kenf@mallfinder.com)
* @version 1, September 30, 2005
*/

function arrayFindSorted(arrayX, value)
{
    var m = 0;    
    var found = 0;
    var done = 0;
    var hi = arrayLen(arrayX)+1;
    var lo = 1;
    var i = 1;
    var maxtest = 500;
    do {
        m = (hi + lo) \ 2;
        if (arrayX[m] EQ value)
        {
            found = 1;
            done = 1;
        }
        else
        {
            if ((m EQ lo) or (m EQ hi))
                done = 1; /* not found */
            else
            {    
                if (value LT arrayX[m])
                {
                /* higher */
                    hi = m;
                }
                else
                {
                /* lower */
                    lo = m;
                }
            }
        }
        if (i EQ maxtest)
            {
            done = 1;
            writeoutput("Error! overflow in search");
            }
        else
            i = i + 1;
    } while (done EQ 0);
    if (found)
        return m;
    else
        return 0;
}
</cfscript>

Search CFLib.org


Latest Additions

Alan McCollough Alan McCollough added
forceBoolean
5 day(s) ago

Shawn Porter Shawn Porter added
DeMoronize
8 day(s) ago

Chris Carey Chris Carey added
readPropertiesFi...
9 day(s) ago

Randy Johnson Randy Johnson added
lastDayofWeek
11 day(s) ago

Top Rated

Barney Boisvert indentXml
Rated 5.0, 4 time(s)

James Sleeman                                     QuickSort
Rated 5.0, 3 time(s)

Nathan Dintenfass                                 queryColumnsToSt...
Rated 5.0, 3 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 3 time(s)

Created by Raymond Camden / Design by Justin Johnson