5. C) With the help of suitable example explain the working of Binary Search technique.
Answer:
Binary Search:
Binary search works on sorted arrays. A binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned. If the target value is less than or greater than the middle element, the search continues in the lower or upper half of the array, respectively, eliminating the other half from consideration
.In computer science, binary search, also known as half-interval search or logarithmic search is a search algorithm that finds the position of a target value within a sorted array.
Working of binary search with Example:
Working:
The binary search works in the following manner:
- The search process initiates by locating the middle element of the sorted array of data
- After that, the key value is compared with the element
- If the key value is smaller than the middle element, then searches analyses the upper values to the middle element for comparison and matching
- In case the key value is greater than the middle element then searches analyses the lower values to the middle element for comparison and matching
Example:
Array of 10 digits:
[6, 8, 17, 21, 24, 45, 59, 63, 76, 89]
find data: 59
- You have an array of 10 digits, and the element 59 needs to be found.
- All the elements are marked with the index from 0 – 9. Now, the middle of the array is calculated. To do so, you take the left and rightmost values of the index and divide them by 2. The result is 4.5, but we take the floor value. Hence the middle is 4.
- The algorithm drops all the elements from the middle (4) to the lowest bound because 59 is greater than 24, and now the array is left with 5 elements only.
- Now, 59 is greater than 45 and less than 63. The middle is 7. Hence the right index value becomes middle – 1, which equals 6, and the left index value remains the same as before, which is 5.
- At this point, you know that 59 comes after 45. Hence, the left index, which is 5, becomes mid as well.
- These iterations continue until the array is reduced to only one element, or the item to be found becomes the middle of the array.