Search in Sorted Array in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Search in Sorted Array in C: Binary Search Program

📑 On this page:
  • Introduction
  • C Program for Binary Search
  • Sample Output
  • Program Explanation
  • Algorithm
  • Recursive Binary Search
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What is binary search and how it works
  • How to implement binary search in C
  • How binary search is faster than linear search
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to search an element in a sorted array using binary search.

Binary search is a fast searching algorithm that works on sorted arrays. It works by repeatedly dividing the search interval in half. If the target value is less than the middle element, the search continues in the left half; otherwise, it continues in the right half.

Binary search is used in many real-world applications, such as:

  • Searching in a phonebook (sorted by name)
  • Finding a word in a dictionary
  • Searching in a sorted database
  • Finding an element in a sorted list

💡 Key Point: Binary search is much faster than linear search. It has a time complexity of O(log n) compared to O(n) for linear search. However, the array must be sorted before using binary search.

C Program for Binary Search in Sorted Array

#include <stdio.h>

int main() {
    int n, i, search;
    int low, high, mid;
    int found = 0;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array
    int arr[n];
    
    // Read sorted elements into the array
    printf("Enter %d sorted elements (ascending order):\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Get element to search
    printf("\nEnter the element to search: ");
    scanf("%d", &search);
    
    // Binary search
    low = 0;
    high = n - 1;
    
    while(low <= high) {
        mid = (low + high) / 2;
        
        if(arr[mid] == search) {
            printf("\nElement %d found at position %d (index %d)\n", 
                   search, mid + 1, mid);
            found = 1;
            break;
        }
        else if(arr[mid] < search) {
            low = mid + 1;  // Search in right half
        }
        else {
            high = mid - 1;  // Search in left half
        }
    }
    
    // If element not found
    if(found == 0) {
        printf("\nElement %d not found in the array.\n", search);
    }
    
    return 0;
}

Sample Output

Enter the number of elements: 7
Enter 7 sorted elements (ascending order):
10 20 30 40 50 60 70

Enter the element to search: 50

Element 50 found at position 5 (index 4)

When Element is Not Found:

Enter the number of elements: 6
Enter 6 sorted elements (ascending order):
10 20 30 40 50 60

Enter the element to search: 100

Element 100 not found in the array.

Example with Even Number of Elements:

Enter the number of elements: 8
Enter 8 sorted elements (ascending order):
10 20 30 40 50 60 70 80

Enter the element to search: 30

Element 30 found at position 3 (index 2)

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — number of elements
    • int i; — loop counter
    • int search; — element to search for
    • int low, high, mid; — pointers for binary search
    • int found = 0; — flag (0 = not found, 1 = found)
  3. Get User Input: Reads the sorted array elements from the user.
  4. Get Search Element: Asks the user for the element to search.
  5. Binary Search:
    • Initialize: low = 0, high = n - 1
    • While low <= high:
      • Calculate mid = (low + high) / 2
      • If arr[mid] == search, element found!
      • If arr[mid] < search, search in right half: low = mid + 1
      • If arr[mid] > search, search in left half: high = mid - 1
  6. Handle Not Found: If found == 0, prints "Element not found".
  7. Return: return 0; indicates successful program execution.

📝 Note: Binary search requires the array to be sorted in ascending order. If the array is in descending order, modify the comparison logic accordingly.

Binary Search Algorithm

Step-by-step algorithm:

  1. Start
  2. Read the sorted array elements
  3. Read the element to search (target)
  4. Set low = 0, high = n - 1
  5. While low <= high:
    • Set mid = (low + high) / 2
    • If arr[mid] == target:
      • Print "Element found at position"
      • Set found = 1
      • Break the loop
    • Else If arr[mid] < target:
      • Set low = mid + 1
    • Else:
      • Set high = mid - 1
  6. If found == 0:
    • Print "Element not found"
  7. End

Visual Example

Searching for 50 in the array [10, 20, 30, 40, 50, 60, 70]:

Step 1: low = 0, high = 6, mid = 3

Check arr[3] = 40 → 40 < 50, so search right half

Step 2: low = 4, high = 6, mid = 5

Check arr[5] = 60 → 60 > 50, so search left half

Step 3: low = 4, high = 4, mid = 4

Check arr[4] = 50 → Match found!

Result: Element found at position 5 (index 4)

Recursive Binary Search

Binary search can also be implemented recursively for a cleaner, more elegant solution:

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int search) {
    if(low <= high) {
        int mid = (low + high) / 2;
        
        if(arr[mid] == search) {
            return mid;  // Element found
        }
        else if(arr[mid] < search) {
            return binarySearch(arr, mid + 1, high, search);  // Search right half
        }
        else {
            return binarySearch(arr, low, mid - 1, search);  // Search left half
        }
    }
    return -1;  // Element not found
}

int main() {
    int n, i, search, result;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d sorted elements (ascending order):\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    printf("\nEnter the element to search: ");
    scanf("%d", &search);
    
    result = binarySearch(arr, 0, n - 1, search);
    
    if(result != -1) {
        printf("\nElement %d found at position %d (index %d)\n", 
               search, result + 1, result);
    } else {
        printf("\nElement %d not found in the array.\n", search);
    }
    
    return 0;
}

Time and Space Complexity

Scenario Time Complexity
Best Case (Element at middle) O(1)
Worst Case (Element not found) O(log n)
Average Case O(log n)
Space Complexity (Iterative) O(1)
Space Complexity (Recursive) O(log n)

Linear Search vs Binary Search

Feature Linear Search Binary Search
Array Requirement Sorted or Unsorted Sorted
Time Complexity O(n) O(log n)
Speed Slow for large arrays Fast for large arrays
Implementation Simple Moderate
Use Case Small or unsorted arrays Large sorted arrays

💻 Practice Exercise

Challenge 1: Modify the binary search program to search for the first occurrence of an element in a sorted array with duplicates.

Challenge 2: Implement binary search for an array sorted in descending order.

🔍 Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int n, i, search;
    int low, high, mid;
    int result = -1;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d sorted elements (ascending order):\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    printf("\nEnter the element to search: ");
    scanf("%d", &search);
    
    // Binary search for first occurrence
    low = 0;
    high = n - 1;
    
    while(low <= high) {
        mid = (low + high) / 2;
        
        if(arr[mid] == search) {
            result = mid;
            high = mid - 1;  // Continue searching in left half
        }
        else if(arr[mid] < search) {
            low = mid + 1;
        }
        else {
            high = mid - 1;
        }
    }
    
    if(result != -1) {
        printf("\nFirst occurrence of %d found at position %d (index %d)\n", 
               search, result + 1, result);
    } else {
        printf("\nElement %d not found in the array.\n", search);
    }
    
    return 0;
}

Frequently Asked Questions

1. What is binary search in C?

Binary search is a fast searching algorithm that works on sorted arrays. It repeatedly divides the search interval in half until the target element is found or the interval becomes empty.

2. What is the time complexity of binary search?

The time complexity of binary search is O(log n), where n is the number of elements. This is much faster than linear search's O(n).

3. Does binary search work on unsorted arrays?

No, binary search requires a sorted array. If the array is unsorted, you must sort it first or use linear search.

4. What is the difference between iterative and recursive binary search?

Iterative binary search uses a loop and has O(1) space complexity. Recursive binary search uses function calls and has O(log n) space complexity due to the call stack.

5. Can binary search find the first occurrence of a duplicate element?

Yes, by modifying the algorithm to continue searching in the left half even after finding a match, you can find the first occurrence of a duplicate element.

💡 Tip: Binary search is one of the most important algorithms in computer science. Mastering it is essential for technical interviews and efficient programming.

📖 Related Tutorials

  • Linear Search in Array
  • Sort Array in Ascending Order
  • Find Second Largest Element
  • More Array Assignments

Previous Topic: -->> Linear Search in Array   ||   Next topic: -->> Find Second Largest Element


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.