Binary Search

 1) Binary Search

Aim

To search an element in a sorted array using Binary Search in C (without functions).

Objective

  • To apply the concept of divide and conquer.

  • To achieve O(logn)O(\log n)O(logn) search time compared to linear search.

Algorithm

  1. Input number of elements and sorted array.

  2. Set low = 0, high = n-1.

  3. Repeat until low <= high:

    • mid = (low + high) / 2

    • If arr[mid] == key, element is found.

    • Else if arr[mid] < key, search in right half.

    • Else, search in left half.

  4. If not found, print "Element not found".

Flowchart 

flowchart

C Code

#include <stdio.h>

int main() {

    int n, key, low, high, mid, found = 0;

    printf("Enter number of elements: ");

    scanf("%d", &n);

    int arr[n];

    printf("Enter sorted array elements: ");

    for (int i = 0; i < n; i++)

        scanf("%d", &arr[i]);

    printf("Enter element to search: ");

    scanf("%d", &key);

    low = 0;

    high = n - 1;


    while (low <= high) {

        mid = (low + high) / 2;

        if (arr[mid] == key) {

            printf("Element found at index %d\n", mid);

            found = 1;

            break;

        } else if (arr[mid] < key) {

            low = mid + 1;

        } else {

            high = mid - 1;

        }

    }

    if (!found)

        printf("Element not found\n");

    return 0;

}


Comments

Popular posts from this blog

Stack using array

Bubble Sort

Singly linked list implementation