Last active
March 27, 2023 22:32
-
-
Save mk2/9949533 to your computer and use it in GitHub Desktop.
AppleScript: binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use scripting additions | |
set AppleScript's text item delimiters to {", "} | |
-- | |
-- バイナリサーチ | |
-- | |
on binarySearch:aValue withValues:values | |
set res to false | |
set valuesLength to count values | |
set midIndex to valuesLength div 2 | |
-- item 0 of を実行するとエラーになるので、ここでリターン | |
if midIndex = 0 then | |
if aValue = (first item of values) then | |
set res to true | |
end if | |
return res | |
end if | |
set midValue to item midIndex of values | |
log "value is " & values | |
log "values length is " & valuesLength | |
log "mid index is " & midIndex | |
log "mid vlaue is " & midValue | |
if midValue > aValue then | |
set res to (my binarySearch:aValue withValues:(items 1 thru midIndex of values)) | |
else if midValue < aValue then | |
set res to (my binarySearch:aValue withValues:(items (midIndex + 1) thru valuesLength of values)) | |
else if midValue = aValue then | |
set res to true | |
end if | |
return res | |
end binarySearch:withValues: | |
-- | |
-- バイナリサーチテスト | |
-- | |
set values to {1, 2, 3, 6, 7, 9, 11, 13, 15} | |
repeat with i from 1 to (end of values) | |
set searchValue to i | |
log "Search for " & i | |
set result to (my binarySearch:searchValue withValues:values) | |
if result then | |
log "The search value[" & searchValue & "] is found in " & values & "." | |
else | |
log searchValue & " not found." | |
end if | |
end repeat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this. I modified your binary search to always use the complete values list and call itself recursively with different lower and upper indexes. It returns the index of the found item or 0 if not found.