Skip to content

Instantly share code, notes, and snippets.

@oliverdaff
Created July 23, 2013 23:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliverdaff/6067071 to your computer and use it in GitHub Desktop.
Save oliverdaff/6067071 to your computer and use it in GitHub Desktop.
Bash Script Binary Search
binary_search(){
TARGET=$1
TO_SEARCH=(${@:2})
LENGTH=${#TO_SEARCH[@]}
START=0
END=$((LENGTH - 1))
while [[ $START -le $END ]]; do
MIDDLE=$((START + ((END - START)/2)))
ITEM_AT_MIDDLE=${TO_SEARCH[MIDDLE]}
if [[ $ITEM_AT_MIDDLE -gt $TARGET ]]; then
END=$((END-MIDDLE-1))
elif [[ $ITEM_AT_MIDDLE -lt $TARGET ]]; then
START=$((MIDDLE+1))
else
echo $MIDDLE
return 0
fi
done
echo "-1"
return 0
}
@lovasoa
Copy link

lovasoa commented Dec 10, 2016

I coded a more versatile version, that can be used for other types of binary searches (not only searching an element in a bash array): https://gist.github.com/lovasoa/55550cb561110300ad97398d2cf93214

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment