I've been busy for some reason recently ... I don't have a lot of work, but ... why Since the contract expires, I will move the office if I prepare to move. What timing
So the main subject The title is reminiscent of someone wearing red and white border clothes with glasses ...
Challenge the tasks you did before in the morning study today (second time)
array=[1,3,5,6,9,10,13,20,26,31]
Put it out like this I forgot a little and saw the explanation without understanding. A method of taking out the data in the middle, comparing the size on the left and right, narrowing the range by iterative processing, and finally guessing which number. The so-called binary search
So, I was ashamed to say that I learned the word "linear search" for the first time in the content I commented on yesterday's article, and I posted it with the intention of trying this method.
def linear_search(array, num)
array.each_with_index do |n, index|
if n == num
return index
end
end
return
end
array=[1,3,5,6,9,10,13,20,26,31]
puts "Please enter the number you want to search"
num = gets.to_i
result = linear_search(array, num)
if result.nil?
puts "#{num}Does not exist in the array"
else
puts "#{num}Is an array#{result+1}Exists second"
end
* The content pointed out in the comments has been corrected.
Now you can get similar output results. I wasn't aware of words such as linear search, but it felt like I was doing it all the time, so it was easier for me personally.
Congratulations
Recommended Posts