Can be done alone or in pairs Only use programming that we h
Solution
irst off, what is a binary search? A binary search, also known as a half-interval search, is an algorithm that finds a target number in a sorted sequence of numbers by comparing the target number to the middle number in the sequence. If the target number is smaller than the middle number, the entire top half of the sequence is ignored.
Let’s break this down with an example. Let’s say we’re looking for the number 51 in this range of numbers
There are 16 numbers in this sequence, and in computer programming, we begin counting sequences of numbers at 0, which makes the middle number in this sequence 121. In this case, 51 is less than 121, so every number greater than 121, and 121 itself is ignored, making the sequence of numbers look like this:
Now that we have 8 numbers in the sequence, the middle number is 47. Since 51 is a larger number, we can ignore all the numbers 47 on down, leaving us with 15 89 100. Once again we take the middle number, 89. 51 is smaller, so we ignore 89 and 100, leaving us with just 15. If our target number is 15, we have officially found our target.
So how do we write this in C?
First things first, we need an array that holds all 16 numbers:
Next we need to define our own search function:
This function, called search takes in 3 arguments, the target number that you’re looking for,value, the array that you’re searching through, values, and the length of the array, n. This method also returns false (or zero) in the case of success.
Now that we have the function set up, some pseudo-code to get us thinking in the right way:
1 | 0 7 21 34 47 51 89 100 121 151 191 203 500 876 981 1000 |
