# [Ruby] Searching for elements in an array using binary search

## Overview

I thought that I could deepen my understanding by verbalizing things that seem a little complicated. I would appreciate it if you could point out better expressions and mistakes.

--What is binary search? --Search process

--Summary

--References

## What is binary search?

This technique is used to search for data in sorted lists and arrays. We will search by narrowing down the target data to half.

#### Search process

-** Use ** while ** to search repeatedly until the value ** and ** the data you want to search match **

--Is the data you want to search ** to the right of half? Is it on the left? ** ** -Or ** Doesn't it exist in the array? ** **

## Practice

#### problem

Find out if any value exists in the array and what number it exists.

``````def binary_search(ary, target)

left = 0                #Array starts at 0th
right = ary.length - 1  #The end of the array (th)

while left <= right           #Until you find the value you want
center = (left + right) / 2 #Get the middle of the array

if ary[center] == target                              #Once you have the array subscript and the number you want to search for
return "#{target}Is an array#{center + 1}Exists second"  #Return the result with return

elsif ary[center] < target #If the number you want to search is more than half to the right
left = center + 1        #Add 1 to the subscript to search on the right side of the half

else                       #If the number you want to search is more than half to the left
right = center - 1       #Subtract 1 from the subscript to search to the left of the half
end
end

return "#{target}Does not exist in the array" #When the while condition is not met and the search is not found
end

#Array
ary = [1, 3, 5, 6, 9, 14, 24, 33, 45, 53]

#Enter the number you want to search in the terminal
p 'Please enter the number you want to search'

#Because it is a number, to_use i
target = gets.to_i

#Binary the sorted array and the number you want to search_Pass it to the search method.
p binary_search(ary, target)
``````

## Summary

--Binary search is a method used to search data in sorted lists and arrays. --Narrow down the value while dividing it into two