CFLib.org – Common Function Library Project

arrayFindSorted(array, value)

Last updated September 30, 2005

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:

view plain print about
<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:

view plain print about
<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>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Tayo Akinmade Tayo Akinmade added
arrayTrim
4 day(s) ago

Will Belden Will Belden added
longTime
9 day(s) ago

James Sleeman James Sleeman added
quickSort
19 day(s) ago

Ben Forta Ben Forta added
GetHostAddress
22 day(s) ago

Top Rated

Darwan Leonardo Sitepu EksporSQLData
Rated 5.0, 16 time(s)

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 13 time(s)

Barney Boisvert indentXml
Rated 5.0, 10 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson