0% found this document useful (0 votes)
18 views42 pages

Unit III

Uploaded by

mukul.jagtap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views42 pages

Unit III

Uploaded by

mukul.jagtap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

What is Searching?

To search an element in a given array, it can be done in


following ways:

1. Sequential Search or Linear Search


2. Binary 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 value index, else it returns -1.
The above 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.
• 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. As we know binary search is
applied on sorted lists only for fast searching.

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 then move to the right of the list or if the element is greater than
then move to the left of the list. Repeat this, till you find an element.
For example, if searching an element 25 in the 7-element array, following
figure shows how binary search works:
• 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.

• Time complexity of linear search -O(n) , Binary search has time


complexity O(log n).

• Linear search performs equality comparisons 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
Three useful variations on the sequential search
algorithm are:

1) Sentinel search
2) Probability search
3) Ordered list search
• Sentinel Linear Search as the name suggests is a type of
Linear Search where the number of comparisons are reduced as
compared to a traditional linear search.

• When a linear search is performed on an array of size N then


in the worst case a total of N comparisons are made when the
element to be searched is compared to all the elements of the
array and (N + 1) comparisons are made for the index of the
element to be compared so that the index is not out of bounds
of the array which can be reduced in a Sentinel Linear Search.
• In this search, the last element of the array is replaced with the
element to be searched and then the linear search is performed on
the array without checking whether the current index is inside the
index range of the array or not because the element to be searched
will definitely be found inside the array even if it was not present in
the original array since the last element got replaced with it.

• So, the index to be checked will never be out of bounds of the array.
The number of comparisons in the worst case here will be (N + 2).
int last = array[N-1];
array[N-1] = item; // Here item is the search
element.
int i = 0;
while(array[i]!=item) if( (i < N-1) || (item == array[N-1]) )
{ {
i++; cout << " Item Found @ "<<i;
} }
array[N-1] = last; else
{
cout << " Item Not Found";
}
Here we see that the while loop makes only one comparison in each
iteration and it is sure that it will terminate since the last element of
the list is the search element itself. So in the worst case ( if the search
element does not exists in the list ) then there will be at most N+2
comparisons ( N comparisons in the while loop and 2 comparisons in
the if condition). Which is better than ( 2N+1 ) comparisons as found
in Simple Linear Search.

Take note that both the algorithms have time complexity of O(n).
Fibonacci Search is a comparison-based technique that uses
Fibonacci numbers to search an element in a sorted array.

Fibonacci search is an efficient search algorithm based on divide and


conquer principle that can find an element in the given sorted array
with the help of Fibonacci series in O(log N) time complexity.

Similarities with Binary Search:


• Works for sorted arrays
• A Divide and Conquer Algorithm.
• Has Log n time complexity.
Differences with Binary Search:

• Fibonacci Search divides given array in unequal parts

• Binary Search uses division operator to divide range. Fibonacci


Search doesn’t use /, but uses + and -. The division operator may be
costly on some CPUs.

• Fibonacci Search examines relatively closer elements in subsequent


steps. So when input array is big that cannot fit in CPU cache or even
in RAM, Fibonacci Search can be useful.
Let arr[0..n-1] be the input array and element to be searched be x.
1. Find the smallest Fibonacci Number greater than or equal to n. Let this number
be fibM [m’th Fibonacci Number]. Let the two Fibonacci numbers preceding it be
fibMm1 [(m-1)’th Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci Number].
2. While the array has elements to be inspected:
1. Compare x with the last element of the range covered by fibMm2
2. If x matches, return index
3. Else If x is less than the element, move the three Fibonacci variables two
Fibonacci down, indicating elimination of approximately rear two-third of
the remaining array.
4. Else x is greater than the element, move the three Fibonacci variables one
Fibonacci down. Reset offset to index. Together these indicate elimination of
approximately front one-third of the remaining array.
3. Since there might be a single element remaining for comparison, check if fibMm1
is 1. If Yes, compare x with that remaining element. If match, return index.
In this searching method, first of all, an index file is created,
that contains some specific group or division of required record
when the index is obtained, then the partial indexing takes less
time cause it is located in a specified group.

When the user makes a request for specific records it will find
that index group first where that specific record is recorded.
Characteristics of Indexed Sequential Search:

1. In Indexed Sequential Search a sorted index is set aside in


addition to the array.

2. Each element in the index points to a block of elements in


the array or another expanded index.

3. The index is searched 1st then the array and guides the
search in the array.
Sorting is the process ordering a list of element in either
ascending or descending order.

A Sorting Algorithm is used to rearrange a given array or list


elements according to a comparison operator on the elements.
The comparison operator is used to decide the new order of
element in the respective data structure.
The below list of characters is sorted in increasing order of their
ASCII values. That is, the character with lesser ASCII value will
be placed first than the character with higher ASCII value.
There are two types of sorting :

1. Internal Sorting
2. External Sorting
Any sort algorithm that uses main memory exclusively during
the sorting is called as internal sort algorithm.

Internal sorting is faster than external sorting.


Internal Sorting Techniques :

1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort
5. Shell Sort
6. Heap Sort
7. Radix Sort
8. Bucket Sort
Any sort algorithm that uses external memory, such as tape or
disk , during the sorting is called as external sort algorithm.

Merge sort is used in external sorting.


A sorting method is said to be stable if at the end of the
method, identical elements occur in the same relative order as
in the original unsorted set.

Example :
Sort efficiency is a measure of the relative efficiency of a sort

It is usually an estimate of the number of comparisons and data


movement required to sort the data.
During the sorted process, the data is traversed many times

Each traversal of the data is referred to as a sort pass.

In addition, the characteristic of a sort pass is the placement of


one or more elements in a sorted list.
Bubble Sort is the simplest sorting algorithm that works by
repeatedly swapping the adjacent elements if they are in wrong
order.
Example:

First Pass:

( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first


two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already
in order (8 > 5), algorithm does not swap them.
Second Pass:

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not
know if it is completed. The algorithm needs one whole pass
without any swap to know it is sorted.
Third Pass:

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
def bubbleSort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n):

# Last i elements are already in place


for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1


# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

The above function always runs O(n^2) time even if the array is
sorted. It can be optimized by stopping the algorithm if inner
loop didn’t cause any swap.
for j in range(0, n-i-1):

# An optimized version of Bubble Sort # traverse the array from 0 to


def bubbleSort(arr): # n-i-1. Swap if the element
n = len(arr) # found is greater than the
# next element
# Traverse through all array elements if arr[j] > arr[j+1] :
for i in range(n): arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = False swapped = True

# Last i elements are already # IF no two elements were swapped


# in place # by inner loop, then break
if swapped == False:
break

You might also like