📌  相关文章
📜  国际空间研究组织 | ISRO CS 2016 |问题 60(1)

📅  最后修改于: 2023-12-03 14:50:47.640000             🧑  作者: Mango

ISRO CS 2016 Question 60

This program was given as a question in the ISRO CS 2016 recruitment exam. It is a coding question requiring the implementation of a binary search algorithm to find a given element in a sorted array. Below is the problem statement and solution in Python:

Problem Statement

You have been given a sorted array of integers and a search element. Your task is to write a program to implement a binary search algorithm to find the index of the search element in the array, or to return -1 if the element is not present in the array.

Example

Input:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x = 5

Output:

4
Solution

To solve this problem, we can implement a recursive binary search algorithm. We start by checking the middle element of the array to see if it is the search element. If it isn't, we check whether the search element is greater or less than the middle element. If it is greater, we search the right half of the array. If it is less, we search the left half. We keep repeating this process until we find the search element or determine that it is not present in the array.

Here is the Python code for the binary search function:

def binary_search(arr, x, low, high):
    if low <= high:
        mid = (low + high) // 2
        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            return binary_search(arr, x, mid + 1, high)
        else:
            return binary_search(arr, x, low, mid - 1)
    else:
        return -1

To use the binary search function, we simply need to pass in the sorted array, the search element, and the indices of the first and last elements of the array:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x = 5

result = binary_search(arr, x, 0, len(arr) - 1)
print(result)

This will output 4, since the index of 5 in the array is 4.