BS Using C
BS Using C
1. Objective
To develop a program for Binary Search using the Divide and Conquer approach.
To measure and analyze the running time of the Binary Search algorithm.
2. Software Required
3. Algorithm
1. Start with the first index (low) and last index (high) of the array.
2. Calculate the middle index as: mid = (low + high) // 2.
3. If the middle element matches the target, the search is successful.
4. If the target is smaller than the middle element, search in the left sub-array.
5. If the target is larger than the middle element, search in the right sub-array.
6. Repeat steps 2-5 until the element is found or the sub-array reduces to zero.
4. Flowchart / Diagram
Draw the flowchart for binary search with decision steps and loops.
Include conditions like 'target == mid', 'target < mid', and 'target > mid'.
5. Theory
Binary Search is a searching technique that divides the search space into two halves in
every iteration, reducing the problem size significantly.
The time complexity of binary search is O(log n), making it much faster than linear
search for large datasets.
The running time of binary search depends on the size of the input array.
6. Procedure
1. Initialize the sorted array, target value, and low and high indices.
2. Calculate the middle index.
3. Compare the middle element with the target.
4. If the middle element matches the target, return the index.
5. If the target is smaller, move to the left sub-array (update high = mid - 1).
6. If the target is larger, move to the right sub-array (update low = mid + 1).
7. Repeat the process until the target is found or the sub-array size becomes zero.
8. Measure the running time of the program using built-in time functions (like
time.time() in Python).
7. Program
Example C Code: Here’s a C program to implement Binary Search using Divide and
Conquer and measure its running time using the clock() function from the time.h library.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n, key, result;
clock_t start, end;
double cpu_time_used;
Array Size (n) Target Element Index Found Time Taken (seconds)
5 10 3 0.00002
10 40 9 0.00004
100 78 76 0.00012
Plot the graph of Array Size (n) vs. Time Taken (seconds) to visualize the time
complexity.
The plot should show a logarithmic curve.
Binary search is faster than linear search due to its logarithmic time complexity.
The running time increases as the size of the array increases but follows a logarithmic
growth.
Real-time implementation of binary search can be optimized by using iterative
approaches instead of recursion.
13. Precautions
15. Signature