Skip to content

Instantly share code, notes, and snippets.

@taichi-ishitani
Last active October 26, 2016 03:46
Show Gist options
  • Save taichi-ishitani/8e0c26e3ee80c0eb6685ac9d9dae395f to your computer and use it in GitHub Desktop.
Save taichi-ishitani/8e0c26e3ee80c0eb6685ac9d9dae395f to your computer and use it in GitHub Desktop.
二分検索/Binary Search
int binary_search(int value, int values[], int left_index, int right_index) {
int middle_index = (right_index - left_index) / 2 + left_index;
if (left_index > right_index) {
return -1;
}
else if (value < values[middle_index]) {
return binary_search(value, values, left_index, middle_index - 1);
}
else if (value > values[middle_index]) {
return binary_search(value, values, middle_index + 1, right_index);
}
else {
return middle_index;
}
}
def binary_search(value, values, left_index = nil, right_index = nil)
left_index ||= 0
right_index ||= values.size - 1
middle_index = (right_index - left_index) / 2 + left_index
if left_index > right_index
false
elsif value < values[middle_index]
binary_search(value, values, left_index, middle_index - 1)
elsif value > values[middle_index]
binary_search(value, values, middle_index + 1, right_index)
else
middle_index
end
end
values = (1 .. 999).to_a
p binary_search(0 , values) # false
p binary_search(1 , values) # 0
p binary_search(2 , values) # 1
p binary_search(500 , values) # 499
p binary_search(999 , values) # 998
p binary_search(1000, values) # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment