0
0
DSA Cprogramming~30 mins

Binary Search as Divide and Conquer in DSA C - Build from Scratch

Choose your learning style9 modes available
Binary Search as Divide and Conquer
📖 Scenario: You have a sorted list of book page numbers where a special note is hidden. You want to find the page number quickly using a method that splits the search area in half each time.
🎯 Goal: Build a C program that uses binary search to find a target page number in a sorted array of page numbers.
📋 What You'll Learn
Create a sorted array of integers called pages with the exact values: 2, 5, 8, 12, 16, 23, 38, 56, 72, 91
Create an integer variable called target and set it to 23
Write a function called binary_search that takes the array, its size, and the target, and returns the index of the target or -1 if not found
Print the index returned by binary_search
💡 Why This Matters
🌍 Real World
Binary search is used in many real-world applications like searching in phone books, dictionaries, or databases where data is sorted.
💼 Career
Understanding binary search helps in optimizing search operations in software development, improving performance in data retrieval tasks.
Progress0 / 4 steps
1
Create the sorted array of page numbers
Create an integer array called pages with these exact values: 2, 5, 8, 12, 16, 23, 38, 56, 72, 91.
DSA C
Hint

Use int pages[] = { ... }; to create the array with the exact numbers.

2
Set the target page number
Create an integer variable called target and set it to 23 inside the main function.
DSA C
Hint

Inside main, write int target = 23;.

3
Write the binary search function
Write a function called binary_search that takes int arr[], int size, and int target as parameters. Use a divide and conquer approach with low, high, and mid variables to find the target. Return the index if found, or -1 if not found.
DSA C
Hint

Use a while loop with low and high to narrow down the search. Calculate mid and compare arr[mid] with target.

4
Call binary_search and print the result
Call binary_search with pages, its size 10, and target. Store the result in an integer variable called index. Then print index using printf.
DSA C
Hint

Call binary_search(pages, 10, target), save to index, then print index with printf("%d\n", index);.