SlideShare a Scribd company logo
1 of 5
Binary search
• binary search: An algorithm that searches for a value in a sorted list by
repeatedly eliminating half the list from consideration.
– Can be written iteratively or recursively
– implemented in Java as method Arrays.binarySearch in java.util
package
• Algorithm pseudocode (searching for a value K):
– Start out with the search area being from indexes 0 to length-1.
– Examine the element in the middle of the search area.
• If it is K, stop.
• Otherwise,
– If it is smaller than K, eliminate the upper half of the search area.
– If it is larger than K, eliminate the lower half of the search area.
– Repeat the above examination.
Binary search
• binary search: Locates a target value in a sorted array/list by
successively eliminating half of the array from consideration.
– How many elements will it need to examine? O(log N)
– Can be implemented with a loop or recursively
– Example: Searching the array below for the value 42:
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103
lo mid hi
Binary search example
Using binarySearch
• Java provides two binary search methods:
– Arrays.binarySearch (for an array)
// binary search on an array:
int[] numbers = {-3, 2, 8, 12, 17, 29, 44, 58, 79};
int index = Arrays.binarySearch(numbers, 29);
System.out.println("29 is found at index " + index);
– Collections.binarySearch (for a List)
// binary search on ArrayList with the same values:
int index = Collections.binarySearch(list, 29);
System.out.println("29 is found at index " + index);
– Note that the values in the array / list are in sorted order.
– If they are not, binarySearch is not guaranteed to work properly.
Binary search code
// Returns the index of an occurrence of target in a,
// or a negative number if the target is not found.
// Precondition: elements of a are in sorted order
public static int binarySearch(int[] a, int target) {
int min = 0;
int max = a.length - 1;
while (min <= max) {
int mid = (min + max) / 2;
if (a[mid] < target) {
min = mid + 1;
} else if (a[mid] > target) {
max = mid - 1;
} else {
return mid; // target found
}
}
return -(min + 1); // target not found
}

More Related Content

What's hot

What's hot (20)

Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching 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
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Linear search algorithm
Linear search algorithmLinear search algorithm
Linear search algorithm
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
Sorting
SortingSorting
Sorting
 
Searching linear &amp; binary search
Searching linear &amp; binary searchSearching linear &amp; binary search
Searching linear &amp; binary search
 
Searching
SearchingSearching
Searching
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Binary search
Binary searchBinary search
Binary search
 
Dsa – data structure and algorithms sorting
Dsa – data structure and algorithms  sortingDsa – data structure and algorithms  sorting
Dsa – data structure and algorithms sorting
 
Searching algorithm
Searching algorithmSearching algorithm
Searching algorithm
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Linear search-and-binary-search
Linear search-and-binary-searchLinear search-and-binary-search
Linear search-and-binary-search
 
Fibonacci search
Fibonacci searchFibonacci search
Fibonacci search
 
Demonstrate interpolation search
Demonstrate interpolation searchDemonstrate interpolation search
Demonstrate interpolation search
 
Algorithm and Programming (Searching)
Algorithm and Programming (Searching)Algorithm and Programming (Searching)
Algorithm and Programming (Searching)
 

Viewers also liked (20)

Chap04alg
Chap04algChap04alg
Chap04alg
 
Jumping Into Java Then!
Jumping Into Java Then!Jumping Into Java Then!
Jumping Into Java Then!
 
[ACM-ICPC] Greedy Algorithm
[ACM-ICPC] Greedy Algorithm[ACM-ICPC] Greedy Algorithm
[ACM-ICPC] Greedy Algorithm
 
Greedy Algoritham
Greedy AlgorithamGreedy Algoritham
Greedy Algoritham
 
Greedyalgorithm
Greedyalgorithm Greedyalgorithm
Greedyalgorithm
 
Activity selection problem
Activity selection problemActivity selection problem
Activity selection problem
 
Activity selection problem class 12
Activity selection problem class 12Activity selection problem class 12
Activity selection problem class 12
 
Application of greedy method
Application  of  greedy methodApplication  of  greedy method
Application of greedy method
 
Greedy
GreedyGreedy
Greedy
 
DP
DPDP
DP
 
Greedymethod
GreedymethodGreedymethod
Greedymethod
 
Heap sort
Heap sort Heap sort
Heap sort
 
Heapify
HeapifyHeapify
Heapify
 
chapter - 6.ppt
chapter - 6.pptchapter - 6.ppt
chapter - 6.ppt
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
 
Heap sort
Heap sortHeap sort
Heap sort
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
 
Merge sort
Merge sortMerge sort
Merge sort
 

Similar to 7 searching injava-binary

Algorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAlgorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptx
Aftabali702240
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 

Similar to 7 searching injava-binary (20)

Analysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptxAnalysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptx
 
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
 
Algorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAlgorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptx
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Array ppt
Array pptArray ppt
Array ppt
 
Array.pdf
Array.pdfArray.pdf
Array.pdf
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
Ppt chapter11
Ppt chapter11Ppt chapter11
Ppt chapter11
 
Searching techniques
Searching techniquesSearching techniques
Searching techniques
 
Presentation
PresentationPresentation
Presentation
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
IRJET- A Survey on Different Searching Algorithms
IRJET- A Survey on Different Searching AlgorithmsIRJET- A Survey on Different Searching Algorithms
IRJET- A Survey on Different Searching Algorithms
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Arrays
ArraysArrays
Arrays
 
cs702 ppt.ppt
cs702 ppt.pptcs702 ppt.ppt
cs702 ppt.ppt
 

More from irdginfo

10 merge sort
10 merge sort10 merge sort
10 merge sort
irdginfo
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
irdginfo
 
8 elementary sorts-bubble
8 elementary sorts-bubble8 elementary sorts-bubble
8 elementary sorts-bubble
irdginfo
 
8 elementary sorts-shell
8 elementary sorts-shell8 elementary sorts-shell
8 elementary sorts-shell
irdginfo
 
8 elementary sorts-insertion
8 elementary sorts-insertion8 elementary sorts-insertion
8 elementary sorts-insertion
irdginfo
 
8 elementary sorts-selection
8 elementary sorts-selection8 elementary sorts-selection
8 elementary sorts-selection
irdginfo
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 
5 data structures-hashtable
5 data structures-hashtable5 data structures-hashtable
5 data structures-hashtable
irdginfo
 
5 data structures-tree
5 data structures-tree5 data structures-tree
5 data structures-tree
irdginfo
 
5 data structures-stack
5 data structures-stack5 data structures-stack
5 data structures-stack
irdginfo
 
5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist
irdginfo
 
4 character encoding-unicode
4 character encoding-unicode4 character encoding-unicode
4 character encoding-unicode
irdginfo
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
irdginfo
 
4 character encoding
4 character encoding4 character encoding
4 character encoding
irdginfo
 
3 number systems-floatingpoint
3 number systems-floatingpoint3 number systems-floatingpoint
3 number systems-floatingpoint
irdginfo
 
2 number systems-scientificnotation
2 number systems-scientificnotation2 number systems-scientificnotation
2 number systems-scientificnotation
irdginfo
 
1 number systems-hex
1 number systems-hex1 number systems-hex
1 number systems-hex
irdginfo
 
1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers
irdginfo
 
1 number systems-octal
1 number systems-octal1 number systems-octal
1 number systems-octal
irdginfo
 

More from irdginfo (20)

Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
 
10 merge sort
10 merge sort10 merge sort
10 merge sort
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
 
8 elementary sorts-bubble
8 elementary sorts-bubble8 elementary sorts-bubble
8 elementary sorts-bubble
 
8 elementary sorts-shell
8 elementary sorts-shell8 elementary sorts-shell
8 elementary sorts-shell
 
8 elementary sorts-insertion
8 elementary sorts-insertion8 elementary sorts-insertion
8 elementary sorts-insertion
 
8 elementary sorts-selection
8 elementary sorts-selection8 elementary sorts-selection
8 elementary sorts-selection
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
5 data structures-hashtable
5 data structures-hashtable5 data structures-hashtable
5 data structures-hashtable
 
5 data structures-tree
5 data structures-tree5 data structures-tree
5 data structures-tree
 
5 data structures-stack
5 data structures-stack5 data structures-stack
5 data structures-stack
 
5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist
 
4 character encoding-unicode
4 character encoding-unicode4 character encoding-unicode
4 character encoding-unicode
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
 
4 character encoding
4 character encoding4 character encoding
4 character encoding
 
3 number systems-floatingpoint
3 number systems-floatingpoint3 number systems-floatingpoint
3 number systems-floatingpoint
 
2 number systems-scientificnotation
2 number systems-scientificnotation2 number systems-scientificnotation
2 number systems-scientificnotation
 
1 number systems-hex
1 number systems-hex1 number systems-hex
1 number systems-hex
 
1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers
 
1 number systems-octal
1 number systems-octal1 number systems-octal
1 number systems-octal
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

7 searching injava-binary

  • 1. Binary search • binary search: An algorithm that searches for a value in a sorted list by repeatedly eliminating half the list from consideration. – Can be written iteratively or recursively – implemented in Java as method Arrays.binarySearch in java.util package • Algorithm pseudocode (searching for a value K): – Start out with the search area being from indexes 0 to length-1. – Examine the element in the middle of the search area. • If it is K, stop. • Otherwise, – If it is smaller than K, eliminate the upper half of the search area. – If it is larger than K, eliminate the lower half of the search area. – Repeat the above examination.
  • 2. Binary search • binary search: Locates a target value in a sorted array/list by successively eliminating half of the array from consideration. – How many elements will it need to examine? O(log N) – Can be implemented with a loop or recursively – Example: Searching the array below for the value 42: index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103 lo mid hi
  • 4. Using binarySearch • Java provides two binary search methods: – Arrays.binarySearch (for an array) // binary search on an array: int[] numbers = {-3, 2, 8, 12, 17, 29, 44, 58, 79}; int index = Arrays.binarySearch(numbers, 29); System.out.println("29 is found at index " + index); – Collections.binarySearch (for a List) // binary search on ArrayList with the same values: int index = Collections.binarySearch(list, 29); System.out.println("29 is found at index " + index); – Note that the values in the array / list are in sorted order. – If they are not, binarySearch is not guaranteed to work properly.
  • 5. Binary search code // Returns the index of an occurrence of target in a, // or a negative number if the target is not found. // Precondition: elements of a are in sorted order public static int binarySearch(int[] a, int target) { int min = 0; int max = a.length - 1; while (min <= max) { int mid = (min + max) / 2; if (a[mid] < target) { min = mid + 1; } else if (a[mid] > target) { max = mid - 1; } else { return mid; // target found } } return -(min + 1); // target not found }