SlideShare a Scribd company logo
1 of 25
Download to read offline
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Linear Search
vs
Binary Search
Linear Search vs Binary Search page 2
© Dr. Jonathan (Yahya) Cazalas
Linear Search
 Basic Searching Through an Array
 In CPCS 202 and 203, we studied how to find a
value in an array
 Look at each value in the array
 Compare it to what we’re looking for
 If we see the value we are searching for,
 Return that we’ve found it!
 Return 1 to show the value is in the array
 Otherwise, if we’ve iterated through the entire array
and haven’t located the value,
 Return that the value isn’t in the array
 Return 0 to show the value is not in the array
Linear Search vs Binary Search page 3
© Dr. Jonathan (Yahya) Cazalas
Linear Search
 Basic Searching Through an Array
 Your code should look something like this:
public static boolean search(int[] a, int value) {
for (int i=0; i<a.length; i++) {
if (a[i] == value) {
return true;
}
}
return false;
}
Linear Search vs Binary Search page 4
© Dr. Jonathan (Yahya) Cazalas
Linear Search
 Basic Searching Through an Array
 Some comments:
 The code returns a boolean
 If we find value, we return true
 If we do not find value, we return false
 This is fine (meaning, it works)
 But, what if we want to know where the value
was found?
 Meaning, at what index is the value found?
Linear Search vs Binary Search page 5
© Dr. Jonathan (Yahya) Cazalas
Linear Search
 Basic Searching Through an Array
 Here’s the same code:
 But now, instead of returning a boolean
 We return an int (the index where value is found)
 If value is not found in the array, we return -1
public static int search(int[] a, int value) {
for (int i=0; i<a.length; i++) {
if (a[i] == value) {
return i;
}
}
return -1;
}
Linear Search vs Binary Search page 6
© Dr. Jonathan (Yahya) Cazalas
Linear Search
 Basic Searching Through an Array
 Analyze code:
 Clearly, if the array is unsorted, this algorithm is
optimal
 They ONLY way to be sure that a value isn’t in the array is
to look at every single spot of the array
 Just like you can’t be sure that you DON’T have some
piece of paper or form unless you look through ALL of your
pieces of paper
 But we ask a question:
 Could we find an item in an array faster if it were
already sorted?
Linear Search vs Binary Search page 7
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Number Guessing Game from childhood
 Remember the game you most likely played as
a child
 I have a secret number between 1 and 100.
 Make a guess and I’ll tell you whether your guess is
too high or too low.
 Then you guess again. The process continues until
you guess the correct number.
 Your job is to MINIMIZE the number of guesses you
make.
Linear Search vs Binary Search page 8
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Number Guessing Game from childhood
 What is the first guess of most people?
 50.
 Why?
 No matter the response (too high or too low), the most
number of possible values for your remaining search
is 50 (either from 1-49 or 51-100)
 Any other first guess results in the risk that the
possible remaining values is greater than 50.
 Example: you guess 75
 I respond: too high
 So now you have to guess between 1 and 74
 74 values to guess from instead of 50
Linear Search vs Binary Search page 9
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Number Guessing Game from childhood
 Basic Winning Strategy
 Always guess the number that is halfway between the
lowest possible value in your search range and the
highest possible value in your search range
 Can we now adapt this idea to work for
searching for a given value in an array?
Linear Search vs Binary Search page 10
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Array Search
 We are given the following sorted array:
 We are searching for the value, 19
 So where is halfway between?
 One guess would be to look at 2 and 118 and take
their average (60).
 But 60 isn’t even in the list
 And if we look at the number closest to 60
 It is almost at the end of the array
index 0 1 2 3 4 5 6 7 8
value 2 6 19 27 33 37 38 41 118
Linear Search vs Binary Search page 11
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Array Search
 We quickly realize that if we want to adapt the
number guessing game strategy to searching an
array, we MUST search in the middle INDEX of
the array.
 In this case:
 The lowest index is 0
 The highest index is 8
 So the middle index is 4
Linear Search vs Binary Search page 12
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Array Search
 Correct Strategy
 We would ask, “is the number I am searching for, 19,
greater or less than the number stored in index 4?
 Index 4 stores 33
 The answer would be “less than”
 So we would modify our search range to in between
index 0 and index 3
 Note that index 4 is no longer in the search space
 We then continue this process
 The second index we’d look at is index 1, since (0+3)/2=1
 Then we’d finally get to index 2, since (2+3)/2 = 2
 And at index 2, we would find the value, 19, in the array
Linear Search vs Binary Search page 13
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Binary Search code:
public static boolean binSearch(int[] a, int value) {
int low = 0;
int high = a.length-1;
while (low <= high) {
int mid = (low + high)/2;
if (value == a[mid])
return true; // meaning, “found”
else if (value < a[mid])
high = mid - 1;
else // if (value > a[mid]
low = mid + 1;
}
return false; // this only happens if not found
Linear Search vs Binary Search page 14
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Binary Search code:
 Some Comments
 As with the basic Array Search, this binSearch
method returns a boolean value
 This works just fine
 But it is good to be more informative with your return
values
 Therefore, it is better if we can return the specific
index where the value was found.
 And if it is not found, we return -1
 This signifies that the value was not found in the array.
Linear Search vs Binary Search page 15
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Binary Search code: (returns index if found)
public static int binSearch(int[] a, int value) {
int low = 0;
int high = a.length-1;
while (low <= high) {
int mid = (low + high)/2;
if (value == a[mid])
return mid; // the index of value
else if (value < a[mid])
high = mid - 1;
else // if (value > a[mid]
low = mid + 1;
}
return -1; // this only happens if not found
Linear Search vs Binary Search page 16
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Binary Search code:
 At the end of each array iteration, all we do is
update either low or high
 This modifies our search region
 Essentially halving it
Linear Search vs Binary Search page 17
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Efficiency of Binary Search
 Analysis:
 Let’s analyze how many comparisons (guesses) are
necessary when running this algorithm on an array of
n items
First, let’s try n = 100
 After 1 guess, we have 50 items left,
 After 2 guesses, we have 25 items left,
 After 3 guesses, we have 12 items left,
 After 4 guesses, we have 6 items left,
 After 5 guesses, we have 3 items left,
 After 6 guesses, we have 1 item left
 After 7 guesses, we have 0 items left.
Linear Search vs Binary Search page 18
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Efficiency of Binary Search
 Analysis:
 Notes:
 The reason for the last iteration is because the number of
items left represent the number of other possible values to
search
 We need to reduce this to 0.
 Also, when n is odd, such as when n=25
 We search the middle element, # 13
 There are 12 elements smaller than 13
 And 12 elements bigger than 13
 This is why the number of items is slightly less than ½ in
those cases
Linear Search vs Binary Search page 19
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Efficiency of Binary Search
 Analysis:
 General case:
 After 1 guess, we have n/2 items left
 After 2 guesses, we have n/4 items left
 After 3 guesses, we have n/8 items left
 After 4 guesses, we have n/16 items left
 …
 After k guesses, we have n/2k items left
Linear Search vs Binary Search page 20
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Efficiency of Binary Search
 Analysis:
 General case:
 So, after k guesses, we have n/2k items left
 The question is:
 How many k guesses do we need to make in order to find
our answer?
 Or until we have one and only one guess left to make?
 So we want to get only 1 item left
 If we can find the value that makes the above fraction
equal to 1, then we know that in one more guess, we’ll
narrow down the item
Linear Search vs Binary Search page 21
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Efficiency of Binary Search
 Analysis:
 General case:
 So, after k guesses, we have n/2k items left
 Again, we want only 1 item left
 So set this equal to 1 and solve for k
 This means that a binary search roughly takes log2n
comparisons when searching in a sorted array of n
items
1
2

k
n k
n 2
 n
k 2
log

Linear Search vs Binary Search page 22
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Efficiency of Binary Search
 Analysis:
 Runs in logarithmic (log n) time
 This is MUCH faster than searching linearly
 Consider the following chart:
 Basically, any log n algorithm is SUPER FAST.
n log n
8 3
1024 10
65536 16
1048576 20
33554432 25
1073741824 30
Linear Search vs Binary Search page 23
© Dr. Jonathan (Yahya) Cazalas
Binary Search
WASN’T
THAT
INCREDIBLE!
Linear Search vs Binary Search page 24
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Linear Search
vs
Binary Search

More Related Content

What's hot

Lecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsLecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsAakash deep Singhal
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)Trupti Agrawal
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVLKatang Isip
 
Unit iv(dsc++)
Unit iv(dsc++)Unit iv(dsc++)
Unit iv(dsc++)Durga Devi
 
Sequential & binary, linear search
Sequential & binary, linear searchSequential & binary, linear search
Sequential & binary, linear searchmontazur420
 
Linear search algorithm
Linear search algorithmLinear search algorithm
Linear search algorithmNeoClassical
 
Week 8 (trees)
Week 8 (trees)Week 8 (trees)
Week 8 (trees)amna izzat
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questionsProf. Dr. K. Adisesha
 
Data structures algorithms_tutorial
Data structures algorithms_tutorialData structures algorithms_tutorial
Data structures algorithms_tutorialHarikaReddy115
 
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
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01shaziabibi5
 
12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search treeKrish_ver2
 

What's hot (20)

E2
E2E2
E2
 
Lecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsLecture 9 data structures and algorithms
Lecture 9 data structures and algorithms
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Unit iv(dsc++)
Unit iv(dsc++)Unit iv(dsc++)
Unit iv(dsc++)
 
Sequential & binary, linear search
Sequential & binary, linear searchSequential & binary, linear search
Sequential & binary, linear search
 
Linear search algorithm
Linear search algorithmLinear search algorithm
Linear search algorithm
 
Week 8 (trees)
Week 8 (trees)Week 8 (trees)
Week 8 (trees)
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 
Data structures algorithms_tutorial
Data structures algorithms_tutorialData structures algorithms_tutorial
Data structures algorithms_tutorial
 
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
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01
 
Algorithm and Programming (Searching)
Algorithm and Programming (Searching)Algorithm and Programming (Searching)
Algorithm and Programming (Searching)
 
12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
Binary Search
Binary SearchBinary Search
Binary Search
 

Similar to binary_search

Binary search algorithm
Binary search algorithmBinary search algorithm
Binary search algorithmmaamir farooq
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search AlgorithmFazalRehman79
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhithRj Juhith
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm03446940736
 
Interpolation search
Interpolation searchInterpolation search
Interpolation searchUsr11011
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
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
Searching SortingSearching Sorting
Searching Sortingguest2cb109
 
Chapter 5 searching and sorting handouts with notes
Chapter 5   searching and sorting handouts with notesChapter 5   searching and sorting handouts with notes
Chapter 5 searching and sorting handouts with notesmailund
 
Linear and Binary Search
Linear and Binary SearchLinear and Binary Search
Linear and Binary SearchWinNie Sjr
 

Similar to binary_search (20)

Binary search algorithm
Binary search algorithmBinary search algorithm
Binary search algorithm
 
Searching
SearchingSearching
Searching
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search Algorithm
 
recursion3
recursion3recursion3
recursion3
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm
 
Interpolation search
Interpolation searchInterpolation search
Interpolation search
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Analysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptxAnalysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptx
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Chapter 5 searching and sorting handouts with notes
Chapter 5   searching and sorting handouts with notesChapter 5   searching and sorting handouts with notes
Chapter 5 searching and sorting handouts with notes
 
Searching.ppt
Searching.pptSearching.ppt
Searching.ppt
 
Chapter 11 ds
Chapter 11 dsChapter 11 ds
Chapter 11 ds
 
Buacm 3
Buacm 3Buacm 3
Buacm 3
 
Search techniques and Hashing
Search techniques and HashingSearch techniques and Hashing
Search techniques and Hashing
 
seaching internal 2 ppt
seaching internal 2 pptseaching internal 2 ppt
seaching internal 2 ppt
 
Linear and Binary Search
Linear and Binary SearchLinear and Binary Search
Linear and Binary Search
 

More from Mohamed Elsayed (20)

binary_trees3
binary_trees3binary_trees3
binary_trees3
 
binary_trees2
binary_trees2binary_trees2
binary_trees2
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
 
queues
queuesqueues
queues
 
stacks2
stacks2stacks2
stacks2
 
stacks1
stacks1stacks1
stacks1
 
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
 
recursion2
recursion2recursion2
recursion2
 
recursion1
recursion1recursion1
recursion1
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
linked_lists
linked_listslinked_lists
linked_lists
 
arrays
arraysarrays
arrays
 
introduction
introductionintroduction
introduction
 
heaps2
heaps2heaps2
heaps2
 
heaps
heapsheaps
heaps
 
hash_tables
hash_tableshash_tables
hash_tables
 
graphs
graphsgraphs
graphs
 

Recently uploaded

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

binary_search

  • 1. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Linear Search vs Binary Search
  • 2. Linear Search vs Binary Search page 2 © Dr. Jonathan (Yahya) Cazalas Linear Search  Basic Searching Through an Array  In CPCS 202 and 203, we studied how to find a value in an array  Look at each value in the array  Compare it to what we’re looking for  If we see the value we are searching for,  Return that we’ve found it!  Return 1 to show the value is in the array  Otherwise, if we’ve iterated through the entire array and haven’t located the value,  Return that the value isn’t in the array  Return 0 to show the value is not in the array
  • 3. Linear Search vs Binary Search page 3 © Dr. Jonathan (Yahya) Cazalas Linear Search  Basic Searching Through an Array  Your code should look something like this: public static boolean search(int[] a, int value) { for (int i=0; i<a.length; i++) { if (a[i] == value) { return true; } } return false; }
  • 4. Linear Search vs Binary Search page 4 © Dr. Jonathan (Yahya) Cazalas Linear Search  Basic Searching Through an Array  Some comments:  The code returns a boolean  If we find value, we return true  If we do not find value, we return false  This is fine (meaning, it works)  But, what if we want to know where the value was found?  Meaning, at what index is the value found?
  • 5. Linear Search vs Binary Search page 5 © Dr. Jonathan (Yahya) Cazalas Linear Search  Basic Searching Through an Array  Here’s the same code:  But now, instead of returning a boolean  We return an int (the index where value is found)  If value is not found in the array, we return -1 public static int search(int[] a, int value) { for (int i=0; i<a.length; i++) { if (a[i] == value) { return i; } } return -1; }
  • 6. Linear Search vs Binary Search page 6 © Dr. Jonathan (Yahya) Cazalas Linear Search  Basic Searching Through an Array  Analyze code:  Clearly, if the array is unsorted, this algorithm is optimal  They ONLY way to be sure that a value isn’t in the array is to look at every single spot of the array  Just like you can’t be sure that you DON’T have some piece of paper or form unless you look through ALL of your pieces of paper  But we ask a question:  Could we find an item in an array faster if it were already sorted?
  • 7. Linear Search vs Binary Search page 7 © Dr. Jonathan (Yahya) Cazalas Binary Search  Number Guessing Game from childhood  Remember the game you most likely played as a child  I have a secret number between 1 and 100.  Make a guess and I’ll tell you whether your guess is too high or too low.  Then you guess again. The process continues until you guess the correct number.  Your job is to MINIMIZE the number of guesses you make.
  • 8. Linear Search vs Binary Search page 8 © Dr. Jonathan (Yahya) Cazalas Binary Search  Number Guessing Game from childhood  What is the first guess of most people?  50.  Why?  No matter the response (too high or too low), the most number of possible values for your remaining search is 50 (either from 1-49 or 51-100)  Any other first guess results in the risk that the possible remaining values is greater than 50.  Example: you guess 75  I respond: too high  So now you have to guess between 1 and 74  74 values to guess from instead of 50
  • 9. Linear Search vs Binary Search page 9 © Dr. Jonathan (Yahya) Cazalas Binary Search  Number Guessing Game from childhood  Basic Winning Strategy  Always guess the number that is halfway between the lowest possible value in your search range and the highest possible value in your search range  Can we now adapt this idea to work for searching for a given value in an array?
  • 10. Linear Search vs Binary Search page 10 © Dr. Jonathan (Yahya) Cazalas Binary Search  Array Search  We are given the following sorted array:  We are searching for the value, 19  So where is halfway between?  One guess would be to look at 2 and 118 and take their average (60).  But 60 isn’t even in the list  And if we look at the number closest to 60  It is almost at the end of the array index 0 1 2 3 4 5 6 7 8 value 2 6 19 27 33 37 38 41 118
  • 11. Linear Search vs Binary Search page 11 © Dr. Jonathan (Yahya) Cazalas Binary Search  Array Search  We quickly realize that if we want to adapt the number guessing game strategy to searching an array, we MUST search in the middle INDEX of the array.  In this case:  The lowest index is 0  The highest index is 8  So the middle index is 4
  • 12. Linear Search vs Binary Search page 12 © Dr. Jonathan (Yahya) Cazalas Binary Search  Array Search  Correct Strategy  We would ask, “is the number I am searching for, 19, greater or less than the number stored in index 4?  Index 4 stores 33  The answer would be “less than”  So we would modify our search range to in between index 0 and index 3  Note that index 4 is no longer in the search space  We then continue this process  The second index we’d look at is index 1, since (0+3)/2=1  Then we’d finally get to index 2, since (2+3)/2 = 2  And at index 2, we would find the value, 19, in the array
  • 13. Linear Search vs Binary Search page 13 © Dr. Jonathan (Yahya) Cazalas Binary Search  Binary Search code: public static boolean binSearch(int[] a, int value) { int low = 0; int high = a.length-1; while (low <= high) { int mid = (low + high)/2; if (value == a[mid]) return true; // meaning, “found” else if (value < a[mid]) high = mid - 1; else // if (value > a[mid] low = mid + 1; } return false; // this only happens if not found
  • 14. Linear Search vs Binary Search page 14 © Dr. Jonathan (Yahya) Cazalas Binary Search  Binary Search code:  Some Comments  As with the basic Array Search, this binSearch method returns a boolean value  This works just fine  But it is good to be more informative with your return values  Therefore, it is better if we can return the specific index where the value was found.  And if it is not found, we return -1  This signifies that the value was not found in the array.
  • 15. Linear Search vs Binary Search page 15 © Dr. Jonathan (Yahya) Cazalas Binary Search  Binary Search code: (returns index if found) public static int binSearch(int[] a, int value) { int low = 0; int high = a.length-1; while (low <= high) { int mid = (low + high)/2; if (value == a[mid]) return mid; // the index of value else if (value < a[mid]) high = mid - 1; else // if (value > a[mid] low = mid + 1; } return -1; // this only happens if not found
  • 16. Linear Search vs Binary Search page 16 © Dr. Jonathan (Yahya) Cazalas Binary Search  Binary Search code:  At the end of each array iteration, all we do is update either low or high  This modifies our search region  Essentially halving it
  • 17. Linear Search vs Binary Search page 17 © Dr. Jonathan (Yahya) Cazalas Binary Search  Efficiency of Binary Search  Analysis:  Let’s analyze how many comparisons (guesses) are necessary when running this algorithm on an array of n items First, let’s try n = 100  After 1 guess, we have 50 items left,  After 2 guesses, we have 25 items left,  After 3 guesses, we have 12 items left,  After 4 guesses, we have 6 items left,  After 5 guesses, we have 3 items left,  After 6 guesses, we have 1 item left  After 7 guesses, we have 0 items left.
  • 18. Linear Search vs Binary Search page 18 © Dr. Jonathan (Yahya) Cazalas Binary Search  Efficiency of Binary Search  Analysis:  Notes:  The reason for the last iteration is because the number of items left represent the number of other possible values to search  We need to reduce this to 0.  Also, when n is odd, such as when n=25  We search the middle element, # 13  There are 12 elements smaller than 13  And 12 elements bigger than 13  This is why the number of items is slightly less than ½ in those cases
  • 19. Linear Search vs Binary Search page 19 © Dr. Jonathan (Yahya) Cazalas Binary Search  Efficiency of Binary Search  Analysis:  General case:  After 1 guess, we have n/2 items left  After 2 guesses, we have n/4 items left  After 3 guesses, we have n/8 items left  After 4 guesses, we have n/16 items left  …  After k guesses, we have n/2k items left
  • 20. Linear Search vs Binary Search page 20 © Dr. Jonathan (Yahya) Cazalas Binary Search  Efficiency of Binary Search  Analysis:  General case:  So, after k guesses, we have n/2k items left  The question is:  How many k guesses do we need to make in order to find our answer?  Or until we have one and only one guess left to make?  So we want to get only 1 item left  If we can find the value that makes the above fraction equal to 1, then we know that in one more guess, we’ll narrow down the item
  • 21. Linear Search vs Binary Search page 21 © Dr. Jonathan (Yahya) Cazalas Binary Search  Efficiency of Binary Search  Analysis:  General case:  So, after k guesses, we have n/2k items left  Again, we want only 1 item left  So set this equal to 1 and solve for k  This means that a binary search roughly takes log2n comparisons when searching in a sorted array of n items 1 2  k n k n 2  n k 2 log 
  • 22. Linear Search vs Binary Search page 22 © Dr. Jonathan (Yahya) Cazalas Binary Search  Efficiency of Binary Search  Analysis:  Runs in logarithmic (log n) time  This is MUCH faster than searching linearly  Consider the following chart:  Basically, any log n algorithm is SUPER FAST. n log n 8 3 1024 10 65536 16 1048576 20 33554432 25 1073741824 30
  • 23. Linear Search vs Binary Search page 23 © Dr. Jonathan (Yahya) Cazalas Binary Search WASN’T THAT INCREDIBLE!
  • 24. Linear Search vs Binary Search page 24 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 25. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Linear Search vs Binary Search