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[0] == 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
I thought 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 nil
.
For your information.
577 Who developed the "avformat-59.dll" that comes with FFmpeg?
585 PHP ssh2_scp_send fails to send files as intended
579 Understanding How to Configure Google API Key
574 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
925 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.