5.C Program to search an element using recursive binary search technique(Part B)

C Program to search an element using recursive binary search technique

ALGORITHM :

Step 1: Start
Step 2: Implement the binary_search function that takes the list (my_list), left index (left), right index (right), and the element to be searched (key) as parameters.
Step 3: If left is less than or equal to right:
        a. Calculate mid as (left + right) / 2.
        b. If my_list[mid] is equal to the key, return mid.
        c. If my_list[mid] is greater than the key, recursively call binary_search for the left half (my_list, left, mid - 1).
        d. If my_list[mid] is less than the key, recursively call binary_search for the right half (my_list, mid + 1, right).
Step 4: Input the number of elements (n) and the list of elements (my_list).
Step 5: Input the element to be searched (key).
Step 6: Call binary_search(my_list, 0, n-1, key).
Step 7: If the returned value from binary_search is not -1, display "Element found at position: returned_value+1".
       Otherwise, display "Element not found in the list".
Step 8: End

SOURCE CODE :

#include <stdio.h>
int binarySearch(int arr[], int left, int right, int key) {
    if (right >= left) {
        int middle = left + (right - left) / 2;

        if (arr[middle] == key)
            return middle;

        if (arr[middle] > key)
            return binarySearch(arr, left, middle - 1, key);

        return binarySearch(arr, middle + 1, right, key);
    }

    return -1;
}

int main() {
    int n, key;
    printf("Enter the number of elements in the list: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements (in sorted order): ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Enter the element to search: ");
    scanf("%d", &key);

    int index = binarySearch(arr, 0, n - 1, key);
    if (index != -1)
        printf("Element found at index %d\n", index);
    else
        printf("Element not found in the list.\n");

    return 0;
}


OUTPUT : 

Enter the number of elements in the list: 7
Enter 7 elements (in sorted order): 3 6 12 18 25 36 42
Enter the element to search: 25
Element found at index 4

No comments:

Post a Comment