I tried implementing binary search/half search code in Ruby's own way using recursive.
Could you give me an evaluation rather than a grade? It works correctly, but I was worried about how it was written.
*Assume that you sort in ascending order by bubble_sort(list).
def binary_search(list, target) sorted_list = bubble_sort(list) center=sorted_list.length/2 if sorted_list.length == 1 if sorted_list == target return "found!" else return "not found!" end else if sorted_list [center] == target return "found!" elsif sorted_list [center] <target binary_search (sorted_list [center+1, sorted_list.length-1], target) elsif sorted_list [center] > target binary_search (sorted_list [0, center-1], target) end end end
It's useless to sort bubbles every time, so I think it's better to change the specification to receive only the sorted array.
if sorted_list [center] == target ... elsif sorted_list [center] <target .. elsif sorted_list [center] > target end
else would be all right here at the end, but I'm sorry if I'm wrong.
I think it will be easier to use if you search for the return value and use the array element found.If you can't find it, use
For your information.
© 2023 OneMinuteCode. All rights reserved.