Please rate the recursive code of the binary search written in ruby.

Asked 2 years ago, Updated 2 years ago, 44 views

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

ruby algorithm

2022-09-30 11:30

1 Answers

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.


2022-09-30 11:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.