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
```

2022-09-30 11:30

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

Popular Tags

python x 4628
android x 1593
java x 1493
javascript x 1425
c x 924
c++ x 877
ruby-on-rails x 696
php x 692
python3 x 683
html x 656

Popular Questions

© 2023 OneMinuteCode. All rights reserved.