Linear search and binary search are two common searching algorithms for 1D data structures like arrays. Linear search sequentially scans the entire array to find a match, taking O(n) time in the worst case. Binary search works by dividing the search space in half at each step, taking O(log n) time to find a match in a sorted array. The document provides pseudocode and examples comparing the two approaches.
1. Introduction to searching and sorting algorithms
2. Types of searching algorithms - Linear search and Binary search.
3. Basic iterative sorting - Bubble sort, Selection sort and Insertion sort.
4. Time and space complexity analysis of searching and sorting
algorithms.
Searching algorithms are used to find elements within datasets. Sequential search linearly checks each element until a match is found, taking O(n) time on average. Interval search algorithms like binary search target the center of a sorted structure and divide the search space in half at each step, taking O(log n) time on average. Jump search checks fewer elements than linear search by jumping ahead by a fixed number of steps or block size, typically the square root of the list length. Interpolation search may check non-middle indexes based on the searched value, working best for uniformly distributed sorted data.
•Common Problems Needs Computers
•The Search Problem
•Basic Search Algorithms
–Algorithms used for searching the contents of an array
•Linear or Sequential Search
•Binary Search
•Comparison Between Linear and Binary Search
•Algorithms for solving shortest path problems
–Sequential Search Algorithms
•Depth-First Search
•Breadth First Search
–Parallel or distributed Search Algorithms
•Parallel Depth-First Search
•Parallel Breadth First Search
1. The document discusses searching and hashing algorithms. It describes linear and binary searching techniques. Linear search has O(n) time complexity, while binary search has O(log n) time complexity for sorted arrays.
2. Hashing is described as a technique to allow O(1) access time by mapping keys to table indexes via a hash function. Separate chaining and open addressing are two common techniques for resolving collisions when different keys hash to the same index. Separate chaining uses linked lists at each table entry while open addressing probes for the next open slot.
Binary search is a search algorithm that finds the position of a target value within a sorted array. It works by comparing the target value to the middle element of the array each time, eliminating half of the remaining elements from consideration based on whether the target is less than or greater than the middle element. This process continues, halving the search space each time, until the target is found or the search space is empty, indicating the target is not in the array. Binary search runs in logarithmic time, making it faster than the linear time complexity of linear search.
The document discusses various searching and sorting algorithms. It describes linear search, binary search, selection sort, bubble sort, and heapsort. For each algorithm, it provides pseudocode examples and analyzes their performance in terms of number of comparisons required in the worst case. Linear search requires N comparisons in the worst case, while binary search requires log N comparisons. Selection sort and bubble sort both require approximately N^2 comparisons, while heapsort requires 1.5NlogN comparisons.
The document summarizes four common searching algorithms: sequential search, binary search, interpolation search, and hashing. Sequential search looks at elements in order from first to last. Binary search divides the search space in half at each step. Interpolation search estimates where an element may be located based on value distribution. Hashing uses a hash function to map elements to array indices, handling collisions by probing to next open index.
1. Introduction to searching and sorting algorithms
2. Types of searching algorithms - Linear search and Binary search.
3. Basic iterative sorting - Bubble sort, Selection sort and Insertion sort.
4. Time and space complexity analysis of searching and sorting
algorithms.
Searching algorithms are used to find elements within datasets. Sequential search linearly checks each element until a match is found, taking O(n) time on average. Interval search algorithms like binary search target the center of a sorted structure and divide the search space in half at each step, taking O(log n) time on average. Jump search checks fewer elements than linear search by jumping ahead by a fixed number of steps or block size, typically the square root of the list length. Interpolation search may check non-middle indexes based on the searched value, working best for uniformly distributed sorted data.
•Common Problems Needs Computers
•The Search Problem
•Basic Search Algorithms
–Algorithms used for searching the contents of an array
•Linear or Sequential Search
•Binary Search
•Comparison Between Linear and Binary Search
•Algorithms for solving shortest path problems
–Sequential Search Algorithms
•Depth-First Search
•Breadth First Search
–Parallel or distributed Search Algorithms
•Parallel Depth-First Search
•Parallel Breadth First Search
1. The document discusses searching and hashing algorithms. It describes linear and binary searching techniques. Linear search has O(n) time complexity, while binary search has O(log n) time complexity for sorted arrays.
2. Hashing is described as a technique to allow O(1) access time by mapping keys to table indexes via a hash function. Separate chaining and open addressing are two common techniques for resolving collisions when different keys hash to the same index. Separate chaining uses linked lists at each table entry while open addressing probes for the next open slot.
Binary search is a search algorithm that finds the position of a target value within a sorted array. It works by comparing the target value to the middle element of the array each time, eliminating half of the remaining elements from consideration based on whether the target is less than or greater than the middle element. This process continues, halving the search space each time, until the target is found or the search space is empty, indicating the target is not in the array. Binary search runs in logarithmic time, making it faster than the linear time complexity of linear search.
The document discusses various searching and sorting algorithms. It describes linear search, binary search, selection sort, bubble sort, and heapsort. For each algorithm, it provides pseudocode examples and analyzes their performance in terms of number of comparisons required in the worst case. Linear search requires N comparisons in the worst case, while binary search requires log N comparisons. Selection sort and bubble sort both require approximately N^2 comparisons, while heapsort requires 1.5NlogN comparisons.
The document summarizes four common searching algorithms: sequential search, binary search, interpolation search, and hashing. Sequential search looks at elements in order from first to last. Binary search divides the search space in half at each step. Interpolation search estimates where an element may be located based on value distribution. Hashing uses a hash function to map elements to array indices, handling collisions by probing to next open index.
The document summarizes different searching and sorting algorithms. It discusses linear search and binary search for searching algorithms. It explains that linear search has O(n) time complexity while binary search has O(log n) time complexity. For sorting algorithms, it describes bubble sort, selection sort, and insertion sort. It provides pseudocode to illustrate how each algorithm works to sort a list or array.
The document summarizes sorting and searching algorithms. It describes linear and binary search algorithms and analyzes their performance. It also describes selection sort, bubble sort, and heapsort algorithms. Selection sort has O(n^2) performance while bubble sort and heapsort have comparable performance to selection sort. Heapsort improves on these and has O(nlogn) performance by using a heap data structure implemented as an array.
Binary Search - Design & Analysis of AlgorithmsDrishti Bhalla
Binary search is an efficient algorithm for finding a target value within a sorted array. It works by repeatedly dividing the search range in half and checking the value at the midpoint. This eliminates about half of the remaining candidates in each step. The maximum number of comparisons needed is log n, where n is the number of elements. This makes binary search faster than linear search, which requires checking every element. The algorithm works by first finding the middle element, then checking if it matches the target. If not, it recursively searches either the lower or upper half depending on if the target is less than or greater than the middle element.
Binary search is a searching algorithm that finds the position of a target value within a sorted array. It runs in logarithmic time, making O(log n) comparisons where n is the number of elements. The process starts by finding the middle element of the array and comparing it to the target. If they match, the position is returned. If the target is less than the middle element, the search continues in the lower half. If greater, the search continues in the upper half. This halves the search space at each step, resulting in a runtime that is logarithmic in the size of the array. Binary search is optimal for searching sorted data and widely used to search databases and solve equations.
Unit – VIII discusses searching and hashing techniques. It describes linear and binary searching algorithms. Linear search has O(n) time complexity while binary search has O(log n) time complexity for sorted arrays. Hashing is also introduced as a technique to allow O(1) access time by mapping keys to array indices via a hash function. Separate chaining and open addressing like linear probing and quadratic probing are described as methods to handle collisions during hashing.
This document discusses linear search and binary search algorithms. Linear search sequentially checks each element of an unsorted array to find a target value, resulting in O(n) time complexity. Binary search works on a sorted array, comparing the target to the middle element and recursively searching half the array, requiring O(log n) time. The document provides pseudocode for both algorithms and compares their performance on different sized inputs. It also discusses properties of greedy algorithms and provides an example of when a greedy solution fails to find the optimal result.
Searching Algorithms for students of CS and IT using C++shahidameer8
The document discusses two search algorithms: linear search and binary search. Linear search sequentially checks each element of an array to find a target value, while binary search recursively checks the middle element of a sorted array, eliminating half of the remaining elements with each check. Binary search has a logarithmic time complexity of O(logN) while linear search has a linear time complexity of O(N), making binary search more efficient for sorted data.
Merge sort is a sorting algorithm that uses the divide and conquer technique. It divides the unsorted list into halves, recursively sorts the sub-lists, and then merges the sorted sub-lists into a single sorted list. The key steps are dividing, conquering by recursively sorting the sub-problems, and merging the sorted sub-lists. Merge sort has a time complexity of O(n log n) in all cases (best, average, worst) and requires additional storage space.
This document discusses algorithms and their analysis. It covers linear search, binary search, sorting algorithms, and analyzing time complexity using Big O, Big Theta, and Big Omega notation. Binary search runs in logarithmic time O(log n) while linear search takes linear time O(n). The traveling salesperson problem takes exponential time O(n!) and is considered an inefficient algorithm.
Sorting arranges data in a specific order by comparing elements according to a key value. The main sorting methods are bubble sort, selection sort, insertion sort, quicksort, mergesort, heapsort, and radix sort. Hashing maps data to table indexes using a hash function to provide direct access, with the potential for collisions. Common hash functions include division, mid-square, and folding methods.
Sorting arranges data in a specific order by comparing elements according to a key value. The main sorting methods are bubble sort, selection sort, insertion sort, quicksort, mergesort, heapsort, and radix sort. Hashing maps data to table indexes using a hash function to provide direct access, with the potential for collisions. Common hash functions include division, mid-square, and folding methods.
This document discusses various searching and sorting algorithms. It begins by defining searching as finding an element in a given list. Linear search and binary search are described as two common searching algorithms. Linear search has O(n) time complexity while binary search has O(log n) time complexity but requires a sorted list. The document also discusses different sorting algorithms like bubble sort, insertion sort, and merge sort, and defines key concepts related to sorting like stability, efficiency, and passes.
The document discusses various sorting algorithms. It provides an overview of bubble sort, selection sort, and insertion sort. For bubble sort, it explains the process of "bubbling up" the largest element to the end of the array through successive passes. For selection sort, it illustrates the process of finding the largest element and swapping it into the correct position in each pass to sort the array. For insertion sort, it notes that elements are inserted into the sorted portion of the array in the proper position.
1) Linear search, also called sequential search, is a simple algorithm that checks each element of a list sequentially to find a target value. It has a time complexity of O(n) in the worst case.
2) The best case for linear search is O(1) when the target is found at the first element. The worst case is O(n) when the target is at the end or not in the list at all.
3) Linear search requires only O(1) space since it only needs to store the target element being searched for, regardless of the size of the input list.
The document discusses algorithm complexity and Big O notation. It introduces Big O notation as a way to evaluate and compare algorithms based on how their runtime grows with increasing input size. The key points are: Big O gives the worst-case upper bound growth rate; dominant terms are kept and constants are dropped when determining Big O; sequential steps are added while embedded steps are multiplied; and this allows algorithms to be analyzed and compared based on their asymptotic complexity.
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...Umesh Kumar
The document discusses various sorting and searching algorithms:
- Bubble sort, selection sort, merge sort, quicksort are sorting algorithms that arrange data in a particular order like numerical or alphabetical.
- Linear search and binary search are searching algorithms where linear search sequentially checks each item while binary search divides the data set in half with each comparison.
- Examples are provided to illustrate how each algorithm works step-by-step on sample data sets.
The document summarizes various sorting algorithms:
- Bubble sort works by repeatedly swapping adjacent elements that are in the wrong order until the list is fully sorted. It requires O(n^2) time.
- Insertion sort iterates through the list and inserts each element into its sorted position. It is an adaptive algorithm with O(n) time for nearly sorted inputs.
- Quicksort uses a divide and conquer approach, recursively partitioning the list around a pivot element and sorting the sublists. It has average case performance of O(nlogn) time.
The document summarizes different searching and sorting algorithms. It discusses linear search and binary search for searching algorithms. It explains that linear search has O(n) time complexity while binary search has O(log n) time complexity. For sorting algorithms, it describes bubble sort, selection sort, and insertion sort. It provides pseudocode to illustrate how each algorithm works to sort a list or array.
The document summarizes sorting and searching algorithms. It describes linear and binary search algorithms and analyzes their performance. It also describes selection sort, bubble sort, and heapsort algorithms. Selection sort has O(n^2) performance while bubble sort and heapsort have comparable performance to selection sort. Heapsort improves on these and has O(nlogn) performance by using a heap data structure implemented as an array.
Binary Search - Design & Analysis of AlgorithmsDrishti Bhalla
Binary search is an efficient algorithm for finding a target value within a sorted array. It works by repeatedly dividing the search range in half and checking the value at the midpoint. This eliminates about half of the remaining candidates in each step. The maximum number of comparisons needed is log n, where n is the number of elements. This makes binary search faster than linear search, which requires checking every element. The algorithm works by first finding the middle element, then checking if it matches the target. If not, it recursively searches either the lower or upper half depending on if the target is less than or greater than the middle element.
Binary search is a searching algorithm that finds the position of a target value within a sorted array. It runs in logarithmic time, making O(log n) comparisons where n is the number of elements. The process starts by finding the middle element of the array and comparing it to the target. If they match, the position is returned. If the target is less than the middle element, the search continues in the lower half. If greater, the search continues in the upper half. This halves the search space at each step, resulting in a runtime that is logarithmic in the size of the array. Binary search is optimal for searching sorted data and widely used to search databases and solve equations.
Unit – VIII discusses searching and hashing techniques. It describes linear and binary searching algorithms. Linear search has O(n) time complexity while binary search has O(log n) time complexity for sorted arrays. Hashing is also introduced as a technique to allow O(1) access time by mapping keys to array indices via a hash function. Separate chaining and open addressing like linear probing and quadratic probing are described as methods to handle collisions during hashing.
This document discusses linear search and binary search algorithms. Linear search sequentially checks each element of an unsorted array to find a target value, resulting in O(n) time complexity. Binary search works on a sorted array, comparing the target to the middle element and recursively searching half the array, requiring O(log n) time. The document provides pseudocode for both algorithms and compares their performance on different sized inputs. It also discusses properties of greedy algorithms and provides an example of when a greedy solution fails to find the optimal result.
Searching Algorithms for students of CS and IT using C++shahidameer8
The document discusses two search algorithms: linear search and binary search. Linear search sequentially checks each element of an array to find a target value, while binary search recursively checks the middle element of a sorted array, eliminating half of the remaining elements with each check. Binary search has a logarithmic time complexity of O(logN) while linear search has a linear time complexity of O(N), making binary search more efficient for sorted data.
Merge sort is a sorting algorithm that uses the divide and conquer technique. It divides the unsorted list into halves, recursively sorts the sub-lists, and then merges the sorted sub-lists into a single sorted list. The key steps are dividing, conquering by recursively sorting the sub-problems, and merging the sorted sub-lists. Merge sort has a time complexity of O(n log n) in all cases (best, average, worst) and requires additional storage space.
This document discusses algorithms and their analysis. It covers linear search, binary search, sorting algorithms, and analyzing time complexity using Big O, Big Theta, and Big Omega notation. Binary search runs in logarithmic time O(log n) while linear search takes linear time O(n). The traveling salesperson problem takes exponential time O(n!) and is considered an inefficient algorithm.
Sorting arranges data in a specific order by comparing elements according to a key value. The main sorting methods are bubble sort, selection sort, insertion sort, quicksort, mergesort, heapsort, and radix sort. Hashing maps data to table indexes using a hash function to provide direct access, with the potential for collisions. Common hash functions include division, mid-square, and folding methods.
Sorting arranges data in a specific order by comparing elements according to a key value. The main sorting methods are bubble sort, selection sort, insertion sort, quicksort, mergesort, heapsort, and radix sort. Hashing maps data to table indexes using a hash function to provide direct access, with the potential for collisions. Common hash functions include division, mid-square, and folding methods.
This document discusses various searching and sorting algorithms. It begins by defining searching as finding an element in a given list. Linear search and binary search are described as two common searching algorithms. Linear search has O(n) time complexity while binary search has O(log n) time complexity but requires a sorted list. The document also discusses different sorting algorithms like bubble sort, insertion sort, and merge sort, and defines key concepts related to sorting like stability, efficiency, and passes.
The document discusses various sorting algorithms. It provides an overview of bubble sort, selection sort, and insertion sort. For bubble sort, it explains the process of "bubbling up" the largest element to the end of the array through successive passes. For selection sort, it illustrates the process of finding the largest element and swapping it into the correct position in each pass to sort the array. For insertion sort, it notes that elements are inserted into the sorted portion of the array in the proper position.
1) Linear search, also called sequential search, is a simple algorithm that checks each element of a list sequentially to find a target value. It has a time complexity of O(n) in the worst case.
2) The best case for linear search is O(1) when the target is found at the first element. The worst case is O(n) when the target is at the end or not in the list at all.
3) Linear search requires only O(1) space since it only needs to store the target element being searched for, regardless of the size of the input list.
The document discusses algorithm complexity and Big O notation. It introduces Big O notation as a way to evaluate and compare algorithms based on how their runtime grows with increasing input size. The key points are: Big O gives the worst-case upper bound growth rate; dominant terms are kept and constants are dropped when determining Big O; sequential steps are added while embedded steps are multiplied; and this allows algorithms to be analyzed and compared based on their asymptotic complexity.
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...Umesh Kumar
The document discusses various sorting and searching algorithms:
- Bubble sort, selection sort, merge sort, quicksort are sorting algorithms that arrange data in a particular order like numerical or alphabetical.
- Linear search and binary search are searching algorithms where linear search sequentially checks each item while binary search divides the data set in half with each comparison.
- Examples are provided to illustrate how each algorithm works step-by-step on sample data sets.
The document summarizes various sorting algorithms:
- Bubble sort works by repeatedly swapping adjacent elements that are in the wrong order until the list is fully sorted. It requires O(n^2) time.
- Insertion sort iterates through the list and inserts each element into its sorted position. It is an adaptive algorithm with O(n) time for nearly sorted inputs.
- Quicksort uses a divide and conquer approach, recursively partitioning the list around a pivot element and sorting the sublists. It has average case performance of O(nlogn) time.
Similar to Data Structures Algorithms - Week 3c - Basic Searching Algorithms.pptx (20)
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
Leveraging Generative AI to Drive Nonprofit InnovationTechSoup
In this webinar, participants learned how to utilize Generative AI to streamline operations and elevate member engagement. Amazon Web Service experts provided a customer specific use cases and dived into low/no-code tools that are quick and easy to deploy through Amazon Web Service (AWS.)
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...Diana Rendina
Librarians are leading the way in creating future-ready citizens – now we need to update our spaces to match. In this session, attendees will get inspiration for transforming their library spaces. You’ll learn how to survey students and patrons, create a focus group, and use design thinking to brainstorm ideas for your space. We’ll discuss budget friendly ways to change your space as well as how to find funding. No matter where you’re at, you’ll find ideas for reimagining your space in this session.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
2. Searching
■ Searching is the process of determining
whether or not a given value exists in a
data structure or a storage media.
■ We will discuss two searching methods on
1D (Linear) data structures:
– Linear search
– Binary search.
2
3. Linear Search
■ It is also called as Serial or Sequential
Search.
■ The linear (or sequential) search algorithm
on an array is:
– Sequentially scan the array, comparing each
array item with the searched value.
– If a match is found; return the index of the
matched element; otherwise return NULL.
■ Note: linear search can be applied to both
sorted and unsorted arrays.
3
4. Linear Search
■ Step through array of records, one at a
time.
■ Look for record with matching key.
■ Search stops when
– record with matching key is found
– or when search has examined all records
without success.
4
5. Linear Search
Linear Search ( Array A, KEY)
Step 1: Set i to L
Step 2: While i <= U do
Step 3: if A[i] = KEY then go to step 7
Step 4: Set i to i + 1
Step 5: End While
Step 6: Print “Element not found” & Exit
Step 7: Print “Element x Found at index i”
Step 8: Exit
5
6. Linear Search
procedure linear_search (Array, KEY)
For each item in the Array
If item == KEY
return the item's location
End If
End For
End procedure
6
17. Analysis of Linear Search
Algorithm LinearSearch (Array A[L..U], KEY)
For i = L to U
If A[i] == KEY
return i
End If
End For
return NULL
17
If n is the size of the array,
S(n) = O(1)
18. Analysis of Linear Search
Algorithm LinearSearch (Array A[L..U], KEY)
For i = L to U
If A[i] == KEY
return i
End If
End For
return NULL
18
If n is the size of the array,
the loop will run not more
than “n” times.
In each iteration, it performs
some constant time operations.
T(n) = n.c = O(n)
22. Average Case
■ In the Average Case, the value can be somewhere in the
array.
■ Average Case Time Complexity is the average of Time
Complexities of all the possible inputs.
■ Suppose we have an array of n records.
■ If we search for the first record, then it requires 1
comparison; if the second, then 2 comparisons, and so on.
■ The average of all these searches is:
(1+2+3+4+5+6+7+8+9+…+n+n)/(n+1) = n/2+1 = O(n)22
23. Advantages of Linear Search
■ The linear search is simple.
■ It is easier to understand & implement.
■ It does not require the data to be stored in
any particular order.
23
24. Disadvantages of Linear Search
■ It has a very poor efficiency as it takes lots
of comparisons to find a particular record
in big files.
■ It fails in very large databases especially in
real-time systems.
24
25. Scenario 1
■ Suppose you’re searching for a person in
the phone book. His/Her name starts with
K.
■ You could start at the beginning and keep
flipping pages until you get to the Ks.
■ But you’re more likely to start at a page in
the middle, because you know the Ks are
going to be near the middle of the phone
book.
25
26. Scenario 2
■ Suppose you’re searching for a word in a
dictionary, and it starts with O.
■ Again, you’ll start near the middle.
26
27. Scenario 3
27
2.7 billion monthly active users
■ Suppose you log on to Facebook. When you do,
Facebook has to verify that you have an account
on the site.
■ So, it needs to search for your username in its
database.
■ Let your username is LARAIB – for instance -
Facebook could start from the As and search for
your name.
■ But it makes more sense for it to begin
somewhere in the middle.
28. Binary Search
■ All these cases use the same algorithm to solve the problem:
BINARY SEARCH.
28
29. Binary Search
■ Binary search is a searching algorithm.
■ Its input is a sorted list of elements.
■ If an element you’re looking for is in that list, binary search
returns the position where it’s located.
■ Otherwise, binary search returns NULL.
29
30. Comparison with Linear Search
■ I’m thinking of a number between 1 and 100.
■ You have to try to guess my number in the fewest tries
possible.
■ With every guess, I’ll tell you if your guess is too low, too
high, or correct.
30
31. Comparison with Linear Search
■ Suppose you start guessing like
this: 1, 2, 3, 4 ….
■ Here’s how it would go.
31
32. Comparison with Linear Search
■ Suppose you start guessing like this:
1, 2, 3, 4 ….
■ Here’s how it would go.
32
33. Comparison with Linear Search
■ This is the sequential search.
■ With each guess, you’re eliminating only one number.
■ If my number was 99, it could take you 99 guesses to get
there!
33
35. Comparison with Linear Search
■ You just eliminated half the numbers!
■ Now you know that 1–50 are all too low.
35
36. Comparison with Linear Search
■ Next guess: 75.
■ Too high, but again you cut down half the remaining
numbers!
■ With binary search, you guess the middle number and
eliminate half the remaining numbers every time.
36
38. Comparison with Linear Search
■ This is binary search.
■ Here’s how many numbers you can eliminate every time.
38
39. Comparison with Linear Search
■ Whatever number I’m thinking of, you can guess in a
maximum of
seven guesses—because you eliminate so many numbers with
every guess!
39
40. Comparison with Linear Search
■ Suppose you’re looking for a word in
the dictionary. The dictionary has
240,000 words.
■ In the worst case, how many steps do
you think each search will take?
40
41. Comparison with Linear Search
■ Simple search could take 240,000 steps if the word you’re
looking for is the very last one in the book.
■ With each step of binary search, you cut the number of
words in half until you’re left with only one word.
41
48. Binary Search (Iterative Version)
Algorithm BinarySearch (Array A[L..U], KEY)
While L<=U, do
mid = (L+U)/2
If A[mid] == KEY
return mid
ElseIf A[mid] < KEY
L = mid + 1
Else
U = mid - 1
End If
End While
return NULL
48
49. Binary Search (Recursive Version)
Algorithm BinSearch (Array A, KEY, U, L)
If L>U
return NULL
End If
mid = (L+U)/2
If A[mid] == KEY
return mid
ElseIf A[mid] < KEY
return BinSearch(A, KEY, mid + 1, U)
Else
return BinSearch(A, KEY, L, mid - 1)
End If
49
50. Binary Search – Side by Side
Algorithm BinarySearch (Array A[L..U], KEY)
While L<=U, do
mid = (L+U)/2
If A[mid] == KEY
return mid
ElseIf A[mid] < KEY
L = mid + 1
Else
U = mid - 1
End If
End While
return NULL
50
Algorithm BinSearch (Array A, KEY, U, L)
If L>U
return NULL
End If
mid = (L+U)/2
If A[mid] == KEY
return mid
ElseIf A[mid] < KEY
return BinSearch(A, KEY, mid + 1,
U)
Else
return BinSearch(A, KEY, L, mid -
1)
51. Time Complexity: Comparisons
51
Algorithm BinSearch (Array A, KEY, U, L)
If L>U
return NULL
End If
mid = (L+U)/2
If A[mid] == KEY
return mid
ElseIf A[mid] < KEY
return BinSearch(A, KEY, mid + 1,
U)
Else
return BinSearch(A, KEY, L, mid -
1)
C(n) = C( n/2 ) + c
C(1) = c
C(n) = C(n/2) + c
C(1) = c