Created
July 23, 2013 23:40
-
-
Save oliverdaff/6067071 to your computer and use it in GitHub Desktop.
Bash Script 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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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