Implementation of binary search (recursive and iterative) in C program
Binary search is a search algorithm used to find the position of an element (target value) in a sorted array. The array should be sorted before applying binary search.
Binary search is also called logarithmic search, binary search, and semi-interval search.
Working Principle
The binary search algorithm works by comparing the element to be searched with the middle element of the array, and performs the required process based on the result of this comparison.
Case 1 - element = middle value, find the element and return the index.
Case 2 - element > middle value, searches for an element in the subarray indexed from middle 1 to n.
Case 3 - element
Algorithm
Initial parameter value, end value
Step 1 : Find the middle element of array. using , middle = initial_value + end_value / 2 ; Step 2 : If middle = element, return ‘element found’ and index. Step 3 : if middle > element, call the function with end_value = middle - 1 . Step 4 : if middle < element, call the function with start_value = middle + 1 . Step 5 : exit.
The implementation function of the binary search algorithm uses repeated calling functions. This call can be of two types:
- Iteration
- Recursion
Iteration callis looping the same piece of code multiple times.
Recursive call is to call the same function repeatedly.
A program that uses iterative calls to implement binary search
Example
Demonstration
#include <stdio.h> int iterativeBinarySearch(int array[], int start_index, int end_index, int element){ while (start_index <= end_index){ int middle = start_index + (end_index- start_index )/2; if (array[middle] == element) return middle; if (array[middle] < element) start_index = middle + 1; else end_index = middle - 1; } return -1; } int main(void){ int array[] = {1, 4, 7, 9, 16, 56, 70}; int n = 7; int element = 16; int found_index = iterativeBinarySearch(array, 0, n-1, element); if(found_index == -1 ) { printf("Element not found in the array "); } else { printf("Element found at index : %d",found_index); } return 0; }
Output
Element found at index : 4
Uses recursive calls to implement binary search Program
Example
Online demonstration
#include <stdio.h> int recursiveBinarySearch(int array[], int start_index, int end_index, int element){ if (end_index >= start_index){ int middle = start_index + (end_index - start_index )/2; if (array[middle] == element) return middle; if (array[middle] > element) return recursiveBinarySearch(array, start_index, middle-1, element); return recursiveBinarySearch(array, middle+1, end_index, element); } return -1; } int main(void){ int array[] = {1, 4, 7, 9, 16, 56, 70}; int n = 7; int element = 9; int found_index = recursiveBinarySearch(array, 0, n-1, element); if(found_index == -1 ) { printf("Element not found in the array "); } else { printf("Element found at index : %d",found_index); } return 0; }
Output
Element found at index : 3
The above is the detailed content of Implementation of binary search (recursive and iterative) in C program. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive procedure. A recursive function is a function that calls itself within its definition. If str1 is "Iknowthatyouknowthatiknow" and str2 is "know" the number of occurrences is -3. Let us understand through examples. For example, input str1="TPisTPareTPamTP", str2="TP"; output Countofoccurrencesofasubstringrecursi

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

We take the integer array Arr[] as input. The goal is to find the largest and smallest elements in an array using a recursive method. Since we are using recursion, we will iterate through the entire array until we reach length = 1 and then return A[0], which forms the base case. Otherwise, the current element is compared to the current minimum or maximum value and its value is updated recursively for subsequent elements. Let’s look at various input and output scenarios for this −Input −Arr={12,67,99,76,32}; Output −Maximum value in the array: 99 Explanation &mi

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Recursion is a powerful technique that allows a function to call itself to solve a problem. In C++, a recursive function consists of two key elements: the base case (which determines when the recursion stops) and the recursive call (which breaks the problem into smaller sub-problems ). By understanding the basics and practicing practical examples such as factorial calculations, Fibonacci sequences, and binary tree traversals, you can build your recursive intuition and use it in your code with confidence.

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.
