Welcome back to another great Monday! Hope every had a great weekend.
As we do from time to time we'll be revisiting one of the basics of computer algorithms. Create a function that takes in a sorted array of integers and a number. The function should then return the index of that number in the array. If the number doesn't exist return -1. If there is a duplicate you can return either position.
x = [1,2,4,6,7,8,9,10] binary_basic(x, 4) >> 2
Comments:
Anonymous - 10 years, 2 months ago
C#
function binary_basic(arr, item) { for(var i = 0; i < arr.Count; i++) { if(arr[i] == item) { return i; } }
}
reply permalink
wobblebucket - 10 years, 2 months ago
reply permalink
Jordi - 10 years, 2 months ago
REXX: arr = '1 2 4 6 7 8 9 10' do i = 1 to words(arr) w = word(arr,i) say w':' binary_basic(w,arr) end exit
binary_basic: procedure parse arg s,arr first = 1 last = words(arr) do while first <= last mid = (first+last)%2 if word(arr,mid) == s then, return mid if word(arr,mid) > s then, last = mid-1 else, first = mid+1 end return -1
reply permalink
Jordi - 10 years, 2 months ago
Sorry, didn't know how to format: ''' arr = '1 2 4 6 7 8 9 10' do i = 1 to words(arr) w = word(arr,i) say w':' binary_basic(w,arr) end exit
binary_basic: procedure parse arg s,arr first = 1 last = words(arr) do while first <= last mid = (first+last)%2 if word(arr,mid) == s then, return mid if word(arr,mid) > s then, last = mid-1 else, first = mid+1 end return -1 '''
reply permalink
Anon - 10 years, 2 months ago
Java
reply permalink
Anon - 10 years, 2 months ago
Sorry, in the parameter instead of "int[] x", it should be "int[] array"
reply permalink
asheehan - 10 years, 2 months ago
Tried to do a somewhat crummy binary search in Ruby
reply permalink
David - 10 years, 2 months ago
Here is a binary search in Python 2.7
Demo code included
reply permalink