0% found this document useful (0 votes)
11 views

Unit- 2

Uploaded by

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

Unit- 2

Uploaded by

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

Unit- 2

Searching
• Searching is the process of locating given value position in a list of
values, i.e. search is a process of finding a value in a list of values.
• Search is said to be successful if the element being searched is found
or unsuccessful when the element being searched is not found.
• A search typically answers in either True or False as to whether the
item is present.
Searching Techniques
• Two techniques are used for searching:
1) Linear/ Sequential Search.
2) Binary Search.
Sequential/Linear Search
• A linear search is the basic and simple search algorithm.
• In Linear search, a sequential search is made over all elements one by
one.
• (In other words linear search searches an element or value from an
array till the desired element is not found in sequential order. Every
element is checked and if it is found then that particular item is
returned, otherwise the search continues till the end of the data
collection).
• Searching begins from first element and continues until the desired
element is found or end of the file is reached.

• Linear Search is applied on the unsorted or unordered list when there


are fewer elements in a list.

• worst-case performance, is O(n) (where n is the size of


the array),
working of Linear Search
• Read the search element which is to be searched
• Initially Compare, the search element with the first element in the list.
If both are matching, then display "element found" and terminate the
function
• If both are not matching, then compare search element with the next
element in the list.
• Repeat steps until the search element is compared with the last
element in the list.
• If the last element in the list is also doesn't match, then display
"Element not found" and terminate the function.
Linear Search Algorithm
• A is an array with n elements and searchitem is the element to be searched for.
Step1:LOC=-1
Step 2:for i=0 to n-1 do
Step 3:if(searchitem = = A[i])then
LOC=i
GOTO step 6
Endif
End of for loop
Step 6: if(LOC>=0)then
Display ”searchitem found at position (LOC+1)”
else
Display “searchitem not found”
Endif
Step 7:Exit
Example:
Case I: Element found in the list
Consider the elements 22 11 66 44 where n=4 and the
searchitem=66
i=0 ,LOC = -1
A[i]=22
22 != 66 incremnt i, and i=1
A[i]=11
11!= 66 incremnt i, and i=2
A[2] = =66
LOC=2
Therefore 66 is found in position 3 (LOC+1)
Case II: Element not found in the list
Consider the search item 99 in the above list 22 11 66 44
i=0 ,LOC= -1
A[i]=22
22 != 99 increment i, and i=1
A[i]=11
11!= 99 increment i, and i=2
A[2] =66
66!=99 increment i, and i=3
A[3] =44
44!=99 increment i, and i=4

i is not less than n and LOC=-1 itself. Therefore display searchitem


not found in the list.
• /*Program to perform Linear Search using
iteration*/ for(i=0;i<n;i++)
#include<stdio.h> scanf("%d",&a[i]);
int linear(int[],int,int); printf("Enter the search
element\n");
void main()
scanf("%d",&key);
{
loc=linear(a,n,key);
int i,key,a[20],n,loc=-1; if(loc>=0)
clrscr(); printf("Element found at
%d position\n",loc+1);
printf("Enter the number of elements\n");
scanf("%d",&n); else
printf("Element not
printf("Enter the elements\n"); found\n");
getch();
/*Linear search iterative
function*/ Output:
int linear(int a[10],int n,int Enter the number of
search) elements
{ 3
int i;
Enter the elements
for(i=0;i<n;i++)
33 21 19
{
Enter the search
if(a[i]==search)
element
return(i);
21
}
return(-1); Element found at 2
position
}
• /*Program to perform Linear Search using recursion*/
#include<stdio.h>

int linear(int[],int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search element\n");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d
position\n",loc+1);
/*Linear search recursive
else function*/
printf("Element not found\n");int linear(int a[10],int n,int
search)
getch();
{
} if(n<=0)
return(-1);
else if(a[n-1]==search)
return(n-1);
else
return(linear(a,n-
1,search));
Binary Search Algorithm

• Binary Search Algorithm 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).
Binary search- Example
Step 1: Determine half of the array by using this formula,

Here it is, 0 + (9 - 0) / 2 = 4 (integer value of 4.5). So, 4 is


the mid of the array.

Step 2: Compare the value stored at location 4, with the


value being searched, i.e. 31. We find that the value at
location 4 is 27, which is not a match. As the value is
greater than 27 and we have a sorted array, so we also
know that the target value must be in the upper portion
Step 3: Change the low to mid + 1 and find the new mid
value again.

The new mid is 7 now. We compare the value stored at


location 7 with our target value 31. That is (5 + 9) / 2 = 7.

Step 4: The value stored at location 7 is not a match. So,


the value must be in the lower part from this location.
Step 4: The value stored at location 7 is not a match. So,
the value must be in the lower part from this location.

• Compare the value stored at location 5 with our target


value. The match is found.
• Binary search halves the searchable items and
thus reduces the count of comparisons to be made
to very less numbers.
/*Binary search iterative function*/

int binary(int a[10],int low,int high,int item)


{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(item==a[mid])
return(mid);
else if(item>a[mid])
low=mid+1;
else if(item<a[mid])
high=mid-1;
}
return(-1);
}
/*Binary search recursive function*/
int binary(int a[10],int low,int high,int item)
{
int mid;
if(low>high)
return -1;
mid=(low+high)/2;
if(item==a[mid])
return mid;
else if(item>a[mid])
return binary(a,mid+1,high,item);
else
return binary(a,low,mid-1,item);
}
• Binary Search -Iterative Approach
/*Program to perform Binary Search using iteration*/
#include<stdio.h>
for(i=0;i<n;i++)
int binary(int[],int,int,int);
scanf("%d",&a[i]);
void main()
{ printf("Enter the search element\
int i,key,a[20],n,loc=-1; n");
clrscr(); scanf("%d",&key);
printf("Enter the number of elements\n"); loc=binary(a,0,n-1,key);
scanf("%d",&n); if(loc>=0)
printf("enter the elements\n");
printf("Element found at %d
position\n",loc+1);
else
printf("Element not found\n");
getch();
Difference Between Linear Search
And Binary Search
Linear Search Binary Search

Number of comparisons made to search for an Number of comparisons made to search for an
element is more. element is less.

This method does not require list to be sorted. This method can work only on sorted list.

This algorithm is slower. This algorithm is fast.


Basis of comparison Linear / Sequential Search Binary Search
Linear search is an algorithm to find an
Binary search is an algorithm that finds the
element in a list by sequentially checking the
Description position of a target value within a sorted array.
elements of the list until finding the matching
element.

A linear search scans one item at a time A binary search cuts down the search to half as
How It Works
without skipping to any item. soon as the middle of a sorted list is found.

Linear searches may be implemented on any Binary searches can only be implemented on
Implementation linear container (vector, Single Linked list, data structures where two-way traversal is
double linked list). possible.
Dimensional array It can be implemented on both a single and It can be implemented only on a
multidimensional array. multidimensional array.

Algorithm type Iterative in nature Divide and conquer in nature


Usefulness Easy to use and no need for any ordered Anyhow tricky algorithm and elements should
elements. be organized in order.
SORTING
• Sorting refers to arranging data in a particular format.
• Sorting algorithm specifies the way to arrange data in
a particular order.
• Most common orders are in numerical or lexicographical
order.
Importance of sorting
• The importance of sorting lies in the fact that data
searching can be optimized to a very high level, if data
is stored in a sorted manner.

• Sorting is also used to represent data in more readable


formats.
• Following are some of the examples of sorting in real-
life scenarios −

• Telephone Directory − The telephone directory stores


the telephone numbers of people sorted by their names,
so that the names can be searched easily.

• Dictionary − The dictionary stores words in an


alphabetical order so that searching of any word
becomes easy.
Types of sorting
• In-place Sorting and Not-in-place Sorting

Sorting algorithms may require some extra space for


comparison and temporary storage of few data elements.
These algorithms do not require any extra space and sorting
is said to happen in-place, or for example, within the array
itself. This is called in-place sorting.

Example: Bubble sort


• some sorting algorithms, the program requires space
which is more than or equal to the elements being
sorted. Sorting which uses equal or more space is
called not-in-place sorting.

• example : Merge-sort
Stable and Not Stable Sorting
• If a sorting algorithm, after sorting the contents, does
not change the sequence of similar content in which
they appear, it is called stable sorting.

If a sorting algorithm, after sorting the contents,
changes the sequence of similar content in which they
appear, it is called unstable sorting.
Adaptive and Non-Adaptive Sorting Algorithm

• A sorting algorithm is said to be adaptive, if it takes


advantage of already 'sorted' elements in the list that is to
be sorted.

• A non-adaptive algorithm is one which does not take into


account the elements which are already sorted. They try
to force every single element to be re-ordered to confirm
their sorted ness.
Bubble Sort Algorithm
• Bubble sort is a simple sorting algorithm. This sorting
algorithm is comparison-based algorithm in which each
pair of adjacent elements is compared and the elements
are swapped if they are not in order.

• This algorithm is not suitable for large data sets.

• as its average and worst case complexity are of O(n2)


where n is the number of items.
We assume list is an array of n elements.
 that swap function swaps the values of the given array
elements.
• Step 1 − Check if the first element in the input array is
greater than the next element in the array.
• Step 2 − If it is greater, swap the two elements;
otherwise move the pointer forward in the array.
• Step 3 − Repeat Step 2 until we reach the end of the
array.
• Step 4 − Check if the elements are sorted; if not,
repeat the same process (Step 1 to Step 3) from the last
element of the array to the first.
• Step 5 − The final output achieved is the sorted array.
Example
We take an unsorted array for our example.
Bubble sort takes Ο(n2) time so we're keeping it short and precise.

Bubble sort starts with very first two elements,


comparing them to check which one is greater.
• In this case, value 33 is greater than 14, so it is already
in sorted locations. Next, we compare 33 with 27.

• We find that 27 is smaller than 33 and these two values


must be swapped.
• Next we compare 33 and 35. We find that both are in already
sorted positions.

• Then we move to the next two values, 35 and 10.

• We know then that 10 is smaller 35. Hence they are not sorted. We
swap these values. We find that we have reached the end of the
array. After one iteration, the array should look like this −
• we are now showing how an array should look like after
each iteration. After the second iteration, it should look
like this −
• after each iteration, at least one value moves at the
end.
• And when there's no swap required, bubble sort learns
that an array is completely sorted.
Bubble Sort- Algorithm
Assume list is an array of n elements. The swap function
swaps the values of the given array elements.
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
• Complexity Analysis of Bubble Sort:
• Time Complexity: O(n2)

• Auxiliary Space: O(1)


Advantages of Bubble Sort:

• Bubble sort is easy to understand and implement.

• It does not require any additional memory space.

• It is a stable sorting algorithm, meaning that elements


with the same key value maintain their relative order in
the sorted output.
Disadvantages of Bubble Sort:

• Bubble sort has a time complexity of O(n2) which makes


it very slow for large data sets.

• Bubble sort has almost no or limited real world


applications. It is mostly used in academics to teach
different ways of sorting.
DATA STRUCTURES
SELECTION SORT

• Ms. Shiny T L
• Assistant Professor of Physical Sciences
• Kristu Jayanti College, Autonomous
SELECTION SORT

• Selection Sort is a comparison-based sorting

algorithm. It sorts an array by repeatedly selecting

the smallest (or largest) element from the unsorted

portion and swapping it with the first unsorted element.

This process continues until the entire array is sorted.


1.First we find the smallest element and swap it
with the first element. This way we get the
smallest element at its correct position.

2.Then we find the smallest among remaining


elements (or second smallest) and swap it with
the second element.

3.We keep doing this until we get all elements


moved to correct position.
U
YO
K
N
A
T H
Complexity Analysis of Selection Sort

• Time Complexity: O(n2) ,as there are two nested


loops:
• One loop to select an element of Array one by one =
O(n)
• Another loop to compare that element with every other
Array element = O(n)
• Therefore overall complexity = O(n) * O(n) = O(n*n) =
O(n2)

• Auxiliary Space: O(1) as the only extra memory used


is for temporary variables.
Advantages of Selection Sort

• Easy to understand and implement, making it ideal for


teaching basic sorting concepts.
• Requires only a constant O(1) extra memory space.
• It requires less number of swaps (or memory writes)
compared to many other standard algorithms.
Disadvantages of the Selection Sort

• Selection sort has a time complexity of O(n^2) makes it


slower compared to algorithms like Quick Sort or
Merge Sort.

• Does not maintain the relative order of equal elements


which means it is not stable.
Applications of Selection Sort

• Perfect for teaching fundamental sorting mechanisms


and algorithm design.
• Suitable for small lists where the overhead of more
complex algorithms isn’t justified and memory writing is
costly as it requires less memory writes compared to
other standard sorting algorithms.
• Heap Sort algorithm is based on Selection Sort.
Insertion Sort

• Insertion sort is a simple sorting algorithm that works by


iteratively inserting each element of an unsorted list into
its correct position in a sorted portion of the list.

• It is like sorting playing cards in your hands. You split the


cards into two groups: the sorted cards and the unsorted
cards. Then, you pick a card from the unsorted group and
put it in the right place in the sorted group.
• We start with second element of the array as first
element in the array is assumed to be sorted.
• Compare second element with the first element and
check if the second element is smaller then swap them.
• Move to the third element and compare it with the first
two elements and put at its correct position
• Repeat until the entire array is sorted.

You might also like