SlideShare une entreprise Scribd logo
1  sur  8
Binary Search
ALGORITHM
Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do linear search, i.e., start from the leftmost element of arr[] and one by
one compare x with each element of arr[], if x matches with an element, return the index. If x
doesn’t match with any of elements, return -1.
// Linearly search x in arr[]. If x is present then return its
// location, otherwise return -1
int search(int arr[], int n, int x)
{
int i;
for (i=0; i<n; i++)
if (arr[i] == x)
return i;
return -1;
}
The time complexity of above algorithm is O(n).
The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Logn). We basically ignore half of the elements just after one comparison.
1) Compare x with the middle element.
2) If x matches with middle element, we return the mid index.
3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
4) Else (x is smaller) recur for the left half.
Following is Recursive C implementation of Binary Search.
#include <stdio.h>
// A recursive binary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (arr[mid] == x) return mid;
// If element is smaller than mid, then it can only be present
// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present in array
return -1;
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Following is Iterative C implementation of Binary Search.
#include <stdio.h>
// A iterative binary search function. It returns location of x in
// given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r)
{
int m = l + (r-l)/2;
if (arr[m] == x) return m; // Check if x is present at mid
if (arr[m] < x) l = m + 1; // If x greater, ignore left half
else r = m - 1; // If x is smaller, ignore right half
}
return -1; // if we reach here, then element was not present
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}

Contenu connexe

Tendances

PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...Umesh Kumar
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sortingKaushal Shah
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithmsmultimedia9
 
Coin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmCoin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmMd Sadequl Islam
 
Binary search algorithm
Binary search algorithmBinary search algorithm
Binary search algorithmmaamir farooq
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...Dharmendra Prasad
 
Divide and conquer 1
Divide and conquer 1Divide and conquer 1
Divide and conquer 1Kumar
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderAshin Guha Majumder
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhithRj Juhith
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searchingsajinis3
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationZakaria Hossain
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 

Tendances (20)

PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Coin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmCoin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - Algorithm
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Binary search algorithm
Binary search algorithmBinary search algorithm
Binary search algorithm
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
 
Divide and conquer 1
Divide and conquer 1Divide and conquer 1
Divide and conquer 1
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Sorting
SortingSorting
Sorting
 
Sorting algorithm
Sorting algorithmSorting algorithm
Sorting algorithm
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with Animation
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 

En vedette

Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary SearchReem Alattas
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data StructureTalha Shaikh
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Time complexity (linear search vs binary search)
Time complexity (linear search vs binary search)Time complexity (linear search vs binary search)
Time complexity (linear search vs binary search)Kumar
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap SortMohammed Hussein
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmEhsan Ehrari
 
parallel sorting by regular sampling
parallel sorting by regular samplingparallel sorting by regular sampling
parallel sorting by regular samplingWei Mu
 
دور الجامعات2
دور الجامعات2دور الجامعات2
دور الجامعات2arteimi
 
الجودة في التعليم التقني
الجودة في التعليم التقنيالجودة في التعليم التقني
الجودة في التعليم التقنيarteimi
 
UTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIES
UTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIESUTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIES
UTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIESarteimi
 
Linear search Algorithm
Linear search AlgorithmLinear search Algorithm
Linear search Algorithmamit kumar
 
Coding the Matrix: Linear Algebra through Computer Science Applications
Coding the Matrix: Linear Algebra through Computer Science ApplicationsCoding the Matrix: Linear Algebra through Computer Science Applications
Coding the Matrix: Linear Algebra through Computer Science ApplicationsVassilios Rendoumis
 
My paper for philippine conference
My paper for philippine conferenceMy paper for philippine conference
My paper for philippine conferencearteimi
 

En vedette (20)

Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
 
Binary search
Binary searchBinary search
Binary search
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data Structure
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
 
Time complexity (linear search vs binary search)
Time complexity (linear search vs binary search)Time complexity (linear search vs binary search)
Time complexity (linear search vs binary search)
 
Binary Search Algorithm
Binary Search Algorithm Binary Search Algorithm
Binary Search Algorithm
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in Algoritm
 
parallel sorting by regular sampling
parallel sorting by regular samplingparallel sorting by regular sampling
parallel sorting by regular sampling
 
دور الجامعات2
دور الجامعات2دور الجامعات2
دور الجامعات2
 
الجودة في التعليم التقني
الجودة في التعليم التقنيالجودة في التعليم التقني
الجودة في التعليم التقني
 
UTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIES
UTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIESUTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIES
UTILIZING COOPERATIVE LEARNING FOR IT GRADUATE STUDIES
 
Linear search Algorithm
Linear search AlgorithmLinear search Algorithm
Linear search Algorithm
 
Coding the Matrix: Linear Algebra through Computer Science Applications
Coding the Matrix: Linear Algebra through Computer Science ApplicationsCoding the Matrix: Linear Algebra through Computer Science Applications
Coding the Matrix: Linear Algebra through Computer Science Applications
 
R Programming
R ProgrammingR Programming
R Programming
 
certificate
certificatecertificate
certificate
 
My paper for philippine conference
My paper for philippine conferenceMy paper for philippine conference
My paper for philippine conference
 

Similaire à Binary search

Searching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptxSearching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptxStephenRobert15
 
Searching, Sorting and Complexity analysis in DS.pdf
Searching, Sorting and Complexity analysis in DS.pdfSearching, Sorting and Complexity analysis in DS.pdf
Searching, Sorting and Complexity analysis in DS.pdfAkshatMehrotra14
 
In the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfIn the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfarpitaeron555
 
Demonstrate interpolation search
Demonstrate interpolation searchDemonstrate interpolation search
Demonstrate interpolation searchmanojmanoj218596
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrmsMisssaxena
 
27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx
27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx
27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptxAyanMandal44
 
Binary search in ds
Binary search in dsBinary search in ds
Binary search in dschauhankapil
 
DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024RUHULAMINHAZARIKA
 
Data Structures Design Notes.pdf
Data Structures Design Notes.pdfData Structures Design Notes.pdf
Data Structures Design Notes.pdfAmuthachenthiruK
 
RecursiveBinarySearch.pptx
RecursiveBinarySearch.pptxRecursiveBinarySearch.pptx
RecursiveBinarySearch.pptxChingChingErm
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingnikshaikh786
 
ARRAY in python and c with examples .pptx
ARRAY  in python and c with examples .pptxARRAY  in python and c with examples .pptx
ARRAY in python and c with examples .pptxabhishekmaurya102515
 
Unit iv(dsc++)
Unit iv(dsc++)Unit iv(dsc++)
Unit iv(dsc++)Durga Devi
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesswathirajstar
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 

Similaire à Binary search (20)

Searching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptxSearching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptx
 
Searching, Sorting and Complexity analysis in DS.pdf
Searching, Sorting and Complexity analysis in DS.pdfSearching, Sorting and Complexity analysis in DS.pdf
Searching, Sorting and Complexity analysis in DS.pdf
 
Searching
Searching Searching
Searching
 
Binary search
Binary searchBinary search
Binary search
 
binary search
binary searchbinary search
binary search
 
In the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfIn the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdf
 
Linear search
Linear searchLinear search
Linear search
 
Demonstrate interpolation search
Demonstrate interpolation searchDemonstrate interpolation search
Demonstrate interpolation search
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrms
 
27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx
27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx
27631722026_T._TAJESWAR_RAO_PCC-CS301_CSE(CS).pptx
 
Binary search in ds
Binary search in dsBinary search in ds
Binary search in ds
 
Searching
SearchingSearching
Searching
 
DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024
 
Data Structures Design Notes.pdf
Data Structures Design Notes.pdfData Structures Design Notes.pdf
Data Structures Design Notes.pdf
 
RecursiveBinarySearch.pptx
RecursiveBinarySearch.pptxRecursiveBinarySearch.pptx
RecursiveBinarySearch.pptx
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
 
ARRAY in python and c with examples .pptx
ARRAY  in python and c with examples .pptxARRAY  in python and c with examples .pptx
ARRAY in python and c with examples .pptx
 
Unit iv(dsc++)
Unit iv(dsc++)Unit iv(dsc++)
Unit iv(dsc++)
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 

Plus de Raghu nath

Ftp (file transfer protocol)
Ftp (file transfer protocol)Ftp (file transfer protocol)
Ftp (file transfer protocol)Raghu nath
 
Javascript part1
Javascript part1Javascript part1
Javascript part1Raghu nath
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
Selection sort
Selection sortSelection sort
Selection sortRaghu nath
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)Raghu nath
 
Stemming algorithms
Stemming algorithmsStemming algorithms
Stemming algorithmsRaghu nath
 
Step by step guide to install dhcp role
Step by step guide to install dhcp roleStep by step guide to install dhcp role
Step by step guide to install dhcp roleRaghu nath
 
Network essentials chapter 4
Network essentials  chapter 4Network essentials  chapter 4
Network essentials chapter 4Raghu nath
 
Network essentials chapter 3
Network essentials  chapter 3Network essentials  chapter 3
Network essentials chapter 3Raghu nath
 
Network essentials chapter 2
Network essentials  chapter 2Network essentials  chapter 2
Network essentials chapter 2Raghu nath
 
Network essentials - chapter 1
Network essentials - chapter 1Network essentials - chapter 1
Network essentials - chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell ScriptingRaghu nath
 
Adv excel® 2013
Adv excel® 2013Adv excel® 2013
Adv excel® 2013Raghu nath
 

Plus de Raghu nath (20)

Mongo db
Mongo dbMongo db
Mongo db
 
Ftp (file transfer protocol)
Ftp (file transfer protocol)Ftp (file transfer protocol)
Ftp (file transfer protocol)
 
MS WORD 2013
MS WORD 2013MS WORD 2013
MS WORD 2013
 
Msword
MswordMsword
Msword
 
Ms word
Ms wordMs word
Ms word
 
Javascript part1
Javascript part1Javascript part1
Javascript part1
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Selection sort
Selection sortSelection sort
Selection sort
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
 
Stemming algorithms
Stemming algorithmsStemming algorithms
Stemming algorithms
 
Step by step guide to install dhcp role
Step by step guide to install dhcp roleStep by step guide to install dhcp role
Step by step guide to install dhcp role
 
Network essentials chapter 4
Network essentials  chapter 4Network essentials  chapter 4
Network essentials chapter 4
 
Network essentials chapter 3
Network essentials  chapter 3Network essentials  chapter 3
Network essentials chapter 3
 
Network essentials chapter 2
Network essentials  chapter 2Network essentials  chapter 2
Network essentials chapter 2
 
Network essentials - chapter 1
Network essentials - chapter 1Network essentials - chapter 1
Network essentials - chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell Scripting
 
Perl
PerlPerl
Perl
 
Adv excel® 2013
Adv excel® 2013Adv excel® 2013
Adv excel® 2013
 

Binary search

  • 2. Given a sorted array arr[] of n elements, write a function to search a given element x in arr[]. A simple approach is to do linear search, i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1.
  • 3. // Linearly search x in arr[]. If x is present then return its // location, otherwise return -1 int search(int arr[], int n, int x) { int i; for (i=0; i<n; i++) if (arr[i] == x) return i; return -1; }
  • 4. The time complexity of above algorithm is O(n). The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. 1) Compare x with the middle element. 2) If x matches with middle element, we return the mid index. 3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. 4) Else (x is smaller) recur for the left half. Following is Recursive C implementation of Binary Search.
  • 5. #include <stdio.h> // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only be present // in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); // Else the element can only be present in right subarray return binarySearch(arr, mid+1, r, x); } // We reach here when element is not present in array return -1; }
  • 6. int main(void) { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr)/ sizeof(arr[0]); int x = 10; int result = binarySearch(arr, 0, n-1, x); (result == -1)? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0; }
  • 7. Following is Iterative C implementation of Binary Search. #include <stdio.h> // A iterative binary search function. It returns location of x in // given array arr[l..r] if present, otherwise -1 int binarySearch(int arr[], int l, int r, int x) { while (l <= r) { int m = l + (r-l)/2; if (arr[m] == x) return m; // Check if x is present at mid if (arr[m] < x) l = m + 1; // If x greater, ignore left half else r = m - 1; // If x is smaller, ignore right half } return -1; // if we reach here, then element was not present }
  • 8. int main(void) { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr)/ sizeof(arr[0]); int x = 10; int result = binarySearch(arr, 0, n-1, x); (result == -1)? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0; }