Notes On Searching and Sorting
Notes On Searching and Sorting
Searching:
Searching is the process of finding a given value position in a list of values. It decides
whether an element is present in the list or not. It is the algorithmic process of finding
a particular item in a collection of items. It can be done on internal data structure or on
external data structure.
Two types of searching methods are available such as-
1. Sequential Search
2. Binary Search
1. Sequential Search:
Sequential search is also called as Linear Search. Sequential search starts at the
beginning of the list and checks every element of the list. It is a basic and simple
search algorithm. Sequential search compares the element with all the other elements
given in the list. If the element is matched, it returns the address of that value,
otherwise it returns -1.
The following figure shows how sequential search works.
It searches an element or value from an array till the desired element or value is not
found. If we search the element 25, it will go step by step in a sequence order. It
searches in a sequence order. Sequential search is applied on the unsorted or
unordered list when there are fewer elements in a list.
2. Binary Search:
Binary Search is used for searching an element in a sorted array. It is a fast search
algorithm with run-time complexity of O(log n). Binary search works on the principle
of divide and conquer.
This searching technique looks for a particular element by comparing the middle most
element of the collection. It is useful when there are large number of elements in an
array.
The above array is sorted in ascending order. Binary search is applied on sorted lists
only for fast searching.
For example, if searching an element 25 in the 7-element array, following figure
shows how binary search works:
Binary searching starts with middle element. If the element is equal to the element that
we are searching then return true. If the element is less than given element, then move
to the right of the list or if the element is greater than given element, then move to the
left of the list. Repeat this, till you find an element.