You are on page 1of 10

Searching in Arrays

Programming 2

Prepared by: Marie Andrea E. Zurbano,


IT Instructor, PUP Lopez
The process of finding the required data in an array is
called searching.

Normally, there are two types of searching


techniques used in C++
1. Sequential Search
2. Binary Search
Sequential Search

• Sequential search in C++ is also called a linear search.


• This search technique is very simple, to perform this technique the
user starts the loop from the zero index of an array to the last
index of an array.
• It starts from the first index and compared the required value with
the first value.
• If the required value is found it will show the result otherwise
compare the value of next index and it will continue until the
required value is found or loop completes without founding the
value.
Example of Sequential Search:
Binary Search

•Binary search can only be applied on a sorted


array. We cannot apply it on an unsorted array.
•This is a very useful technique because it is used
to quickly found the required values.
Binary search is performed in several steps.

1. Firstly find the middle element of the array and compare with the
value the user wanted to search.
2. If they are same then it will return the location of the required
value.
3. If they are not equal then it will break the array in half
4. If the middle of array is smaller than the required number then it
will search the first half of an array.
5. If the middle of array is greater than the required number then it
will search the second half of an array.
6. This process will continue until the required value is found or until
the loop terminates or complete without finding the required value.
Example of Binary Search:
Important Differences of Linear and Binary
Search

• Input data needs to be sorted in Binary Search and not in Linear


Search
• Linear Search does the sequential access whereas Binary Search
access data randomly
• Linear search performs equality comparison and Binary search
performs ordering comparisons.
Linear Search to find the element “J” in a
given sorted list from A-X
Binary Search to find the element “J” in a
given sorted list from A-X

You might also like