Re: Finding the Position of an item in a list
Re: Finding the Position of an item in a list
- Subject: Re: Finding the Position of an item in a list
- From: Nigel Garvey <email@hidden>
- Date: Mon, 8 Oct 2001 03:02:46 +0100
Greg Back wrote on Sun, 07 Oct 2001 12:57:39 -0400:
>
Hi all-
>
>
Is there any more practical (read "shorter") way to find where in a list a
>
certain item can be found.
>
>
to findPosition(thisItem, thislist)
>
if thisItem is in thislist then
>
repeat with i from 1 to (count thislist)
>
if item i of thislist is thisItem then
>
set j to i
>
exit repeat
>
end if
>
end repeat
>
else
>
set j to "Not in list"
>
end if
>
return j
>
end findPosition
That's about the best way there is for short lists. Last week, I wrote a
binary search handler for this purpose, which, although regrettably not
shorter, might be faster with longer lists:
on listOffset of theItem into theList
if theItem is not in theList then return 0
set {L, R} to {1, count theList}
repeat
if theItem is item L of theList then return L
set M to (L + R) div 2
if theItem is in (items (L + 1) thru M of theList) then
set {L, R} to {L + 1, M}
else
set L to M + 1
end if
end repeat
end listOffset
NG