SlideShare a Scribd company logo
1 of 2
cat > BinarySearch.java
// Java implementation of recursive Binary Search
class BinarySearch {
// Returns index of x if it is present in arr[l..
// r], else return -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;
}
// Driver method to test above
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
//Positive Test Case, Target Element to be searched is found in Array
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
BinarySearch ob1 = new BinarySearch();
//Negative Test Case, Array Range is Finished, Target Element to be
searched is not found in Array
int arr1[] = { 2, 3, 4, 10, 40 };
int n1 = arr1.length;
int x1 = 12;
int result1 = ob1.binarySearch(arr1, 0, n1 - 1, x1);
if (result1 == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result1);
}
}
/* This code is contributed by Rajat Mishra */
^C

More Related Content

What's hot

Python Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and DictionariesPython Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and DictionariesRanel Padon
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismEelco Visser
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL乐群 陈
 
Stl Containers
Stl ContainersStl Containers
Stl Containersppd1961
 
7 searching injava-binary
7 searching injava-binary7 searching injava-binary
7 searching injava-binaryirdginfo
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9dplunkett
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8dplunkett
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)monikadeshmane
 
08 class and object
08   class and object08   class and object
08 class and objectdhrubo kayal
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)Hemant Jain
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryKumar Gaurav
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming LanguageMansiSuthar3
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 

What's hot (20)

Generics in java
Generics in javaGenerics in java
Generics in java
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and DictionariesPython Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and Dictionaries
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
7 searching injava-binary
7 searching injava-binary7 searching injava-binary
7 searching injava-binary
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 
Generics
GenericsGenerics
Generics
 
08 class and object
08   class and object08   class and object
08 class and object
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming Language
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 

Similar to Binary search

Binary search
Binary search Binary search
Binary search Raghu nath
 
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
 
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
 
Java Programming- 1) Write a recursive method that finds and returns t.docx
Java Programming- 1) Write a recursive method that finds and returns t.docxJava Programming- 1) Write a recursive method that finds and returns t.docx
Java Programming- 1) Write a recursive method that finds and returns t.docxmichael1810
 
RecursiveBinarySearch.pptx
RecursiveBinarySearch.pptxRecursiveBinarySearch.pptx
RecursiveBinarySearch.pptxChingChingErm
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...davidwarner122
 
Question 1,2,4 ------------------------------------Please check.pdf
Question 1,2,4 ------------------------------------Please check.pdfQuestion 1,2,4 ------------------------------------Please check.pdf
Question 1,2,4 ------------------------------------Please check.pdfanandhomeneeds
 

Similar to Binary search (9)

Binary search
Binary search Binary 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
 
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
 
Java Programming- 1) Write a recursive method that finds and returns t.docx
Java Programming- 1) Write a recursive method that finds and returns t.docxJava Programming- 1) Write a recursive method that finds and returns t.docx
Java Programming- 1) Write a recursive method that finds and returns t.docx
 
RecursiveBinarySearch.pptx
RecursiveBinarySearch.pptxRecursiveBinarySearch.pptx
RecursiveBinarySearch.pptx
 
Searching.pptx
Searching.pptxSearching.pptx
Searching.pptx
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
Question 1,2,4 ------------------------------------Please check.pdf
Question 1,2,4 ------------------------------------Please check.pdfQuestion 1,2,4 ------------------------------------Please check.pdf
Question 1,2,4 ------------------------------------Please check.pdf
 

Recently uploaded

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 

Recently uploaded (20)

Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 

Binary search

  • 1. cat > BinarySearch.java // Java implementation of recursive Binary Search class BinarySearch { // Returns index of x if it is present in arr[l.. // r], else return -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; } // Driver method to test above public static void main(String args[]) { BinarySearch ob = new BinarySearch(); //Positive Test Case, Target Element to be searched is found in Array int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; int x = 10; int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); BinarySearch ob1 = new BinarySearch(); //Negative Test Case, Array Range is Finished, Target Element to be searched is not found in Array int arr1[] = { 2, 3, 4, 10, 40 }; int n1 = arr1.length; int x1 = 12; int result1 = ob1.binarySearch(arr1, 0, n1 - 1, x1); if (result1 == -1) System.out.println("Element not present");
  • 2. else System.out.println("Element found at index " + result1); } } /* This code is contributed by Rajat Mishra */ ^C