SlideShare a Scribd company logo
1 of 46
SEARCHING
• Searching refers to the operation of
finding the location of a given search
item in the given collection of items.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Linear Search or Sequential search
The most straight forward method of finding a particular element in an unordered list is linear
search. This technique simply involves the comparison of each element of the list in a sequential manner until the
desired element is found.
Algorithm: Linear Search
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
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
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 incremnt i, and i=1
A[i]=11
11!= 99 incremnt i, and i=2
A[2] =66
66!=99 incremnt i, and i=3
A[3] =44
44!=99 incremnt i, and i=4 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Linear Search using iteration*/
#include<stdio.h>
int linear(int[],int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("Enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Linear Search using iteration*/
#include<stdio.h>
int linear(int[],int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("Enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Linear Search using iteration*/
/*Linear search iterative function*/
int linear(int a[10],int n,int search)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==search)
return(i);
}
return(-1);
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Linear Search using iteration*/
/*Linear search iterative function*/
int linear(int a[10],int n,int search)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==search)
return(i);
}
return(-1);
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Linear Search using iteration*/
Output:
Enter the number of elements
3
Enter the elements
33 21 19
Enter the search element
21
Element found at 2 position
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*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 elementsn");
scanf("%d",&n);
printf("enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
} by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Linear search recursive function*/
int linear(int a[10],int n,int search)
{
if(n<0)
return(-1);
else
if(a[n-1]==search)
return(n-1);
else
return(linear(a,n-1,search));
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Complexity of linear search
The complexity of the algorithm is measured by the number of comparisons f(n)
required to find the search element ITEM in the array A consisting of n elements. The worst
case occurs when we search through the entire array A and ITEM does not appear in A.
In this case algorithm requires
f(n)= n+1 comparisons
Thus in the worst case f(n) is proportional to n
The number of comparisons in the average case can be any number 1,2,…. N and
each number occurs with probability P=1/n. then
f (n) = 1.1/n + 2.1/n + ….. n. 1/n
= (1+2+……n). 1/n
= n(n+1)/2. 1/n
= (n+1)/2
Hence f(n) in the average case is approximately equal to half the number of elements in the
list.
In the best case the element can be found in the first comparison itself where f(n)=1.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Swapping and Bubble
Sort Technique
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Swapping: Exchange the contents
G1 G2
Initially (before swapping)
G1: Filled with water
G2: Filled with Milk
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
After Swapping
G1
G2
After swapping
G1: Filled with Milk
G2: Filled with Water
How it
happened?
After Swapping operation
G1: Should be filled with the contents of G2(Milk)
G2: Should be filled with the contents of G1(Water)
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
How Swapping happened
Take an empty glass G3 of same or higher capacity
Step 1: Pour contents of G1 (Water) to the Empty Glass G3
Then G1 will be empty and G3 will have water
G3
G1
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Step 2: Pour contents of G2 (Milk) to the Empty Glass G1
Then G2 will be empty and G1 will have Milk
G1
G2
After swapping
G1: Filled with Milk
G2: Filled with Water
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Step 3: Pour contents of G3 (Water) to the Empty Glass G2
Then G3 will be empty and G2 will have Water
G2
G3
After swapping
G1: Filled with Milk
G2: Filled with Water
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
// Program to swap the contents of two integer variables
#include<stdio.h>
void main()
{
int i=2,j=3,temp;
clrscr();
printf(“n Before Swapping: i = %d t j = %d”,i,j);
temp = i;
i = j;
j = temp
Printf(“n After Swapping: i = %d t j = %d”,i,j);
getch();
}//End of Program
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
•Sorting
• Sorting refers to the operation of arranging the given data items in a specified order either
ascending or descending.
Sorting can be classified as
• Internal sorting – Sorting the records that are stored are in main memory.
• External sorting – records that are sorted are in auxiliary storage.
There are many methods of sorting; some of them are
• Bubble sort
• Insertion sort
• Selection sort
• Merge sort
• Quick sort
• Heap sort
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Efficiency parameters:
The sorting method that is to be implemented depends on how it behaves in each situation. For a given
problem, it is important to know which method will be best suited. Some parameters studied are:
1. Execution time
2. Space or Memory
3. Coding time
• Execution time It is the time required for the execution of the program. This time required is more
if there are more number of comparisons and exchanges of data.
• Space or memory It is the amount of space required to store data.
• Coding time It is the time required to develop a sorting technique for the given problem. It depends
on the complexity of the algorithm.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Complexity function f(n):
Complexity function f(n) is the function which gives the running time of the algorithm in terms of size of the
input data ‘n’.
There are three cases for finding the complexity function f(n).
1. Worst case
In this, maximum number of comparisons are made or maximum value of f(n) is determined.
2. Average case
Average number of comparisons are made or average value of f(n) is determined.
3. Best case
Minimum number of comparisons are made or minimum value of f(n) is determined.
Bubble Sort
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Technique
It works by repeatedly stepping through the list to be sorted,
comparing each pair of adjacent items and swapping them if they
are in the wrong order (the first element is larger than the second
element).
The algorithm gets its name from the way LARGER elements
"bubble" to the top of the list.
Bubble Sort Example – Pass 0
9, 6, 2, 12, 11, 9, 3, 7
6, 9, 2, 12, 11, 9, 3, 7
6, 2, 9, 12, 11, 9, 3, 7
6, 2, 9, 12, 11, 9, 3, 7
6, 2, 9, 11, 12, 9, 3, 7
6, 2, 9, 11, 9, 12, 3, 7
6, 2, 9, 11, 9, 3, 12, 7
6, 2, 9, 11, 9, 3, 7, 12
The 12 is greater than the
7 so they are exchanged.
The 12 is greater than the
3 so they are exchanged.
The twelve is greater than the
9 so they are exchanged
The 12 is larger than the 11
so they are exchanged.
In the third comparison, the 9 is not
larger than the 12 so no exchange
is made. We move on to compare
the next pair without any change to
the list.
Now the next pair of numbers
are compared. Again the 9 is
the larger and so this pair is
also exchanged.
Bubblesort compares the
numbers in pairs from left to
right exchanging when
necessary. Here the first
number 9 is compared to the
second 6 and as it is larger they
are exchanged.
The end of the list has been reached so this
is the end of the first pass. The twelve at the
end of the list must be largest number in the
list and so is now in the correct position. We
now start a new pass from left to right.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 0
Observation I: The Output of Pass 0 is
We Observe that the largest among the given 8 elements is placed in the last location.
Observation II: For executing the Pass 0 for eight elements we had Seven Comparisons
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 0th Pass = 8 – (0 + 1)
= 7
6, 2, 9, 11, 9, 3, 7, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Example – Pass 1
6, 2, 9, 11, 9, 3, 7, 12
2, 6, 9, 11, 9, 3, 7, 12
2, 6, 9, 9, 11, 3, 7, 12
2, 6, 9, 9, 3, 11, 7, 12
2, 6, 9, 9, 3, 7, 11, 12
Notice that this time we do
not have to compare the
last two numbers as we
know the 12 is in position.
This pass therefore only
requires 6 comparisons.
2, 6, 9, 11, 9, 3, 7, 12
2, 6, 9, 11, 9, 3, 7, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 1
Observation I: The Output of Pass 1 is
We Observe that the Second largest among the given 8 elements is placed in the penultimate (second last)
location.
Observation II: For executing the Pass 1 for eight elements we had Six Comparisons
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 1st Pass = 8 – (1 + 1)
= 6
2, 6, 9, 9, 3, 7, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Example – Pass 2
2, 6, 9, 9, 3, 7, 11, 12
2, 6, 9, 3, 9, 7, 11, 12
2, 6, 9, 9, 3, 7, 11, 12
This time the
11 and 12 are
in position.
This pass
therefore only
requires 5
comparisons.
2, 6, 9, 9, 3, 7, 11, 12
2, 6, 9, 9, 3, 7, 11, 12
2, 6, 9, 3, 7, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 2
Observation I: The Output of Pass 2 is
We Observe that the Third largest among the given 8 elements is placed in the last third location.
Observation II: For executing the Pass 2 for eight elements we had Five Comparisons
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 2nd Pass = 8 – (2 + 1)
= 5
2, 6, 9, 3, 7, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Example – Pass 3
2, 6, 9, 3, 7, 9, 11, 12
2, 6, 3, 9, 7, 9, 11, 12
2, 6, 3, 7, 9, 9, 11, 12
Each pass requires fewer
comparisons. This time only
4 are needed.
2, 6, 9, 3, 7, 9, 11, 12
2, 6, 9, 3, 7, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 3
Observation I: The Output of Pass 3 is
We Observe that the Fourth largest among the given 8 elements is placed in the last but fourth location.
Observation II: For executing the Pass 3 for eight elements we had Four Comparisons
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 3rd Pass = 8 – (3 + 1)
= 4
2, 6, 3, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Example – Pass 4
2, 6, 3, 7, 9, 9, 11, 12
2, 3, 6, 7, 9, 9, 11, 12
This pass uses 3
comparisons.
The list is now sorted but
the algorithm does not
know this until it
completes a pass with no
exchanges.
2, 6, 3, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 4
Observation I: The Output of Pass 4 is
We Observe that the Fifth largest among the given 8 elements is placed in the last but fifth location.
Observation II: For executing the Pass 4 for eight elements we had Three Comparisons
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 4th Pass = 8 – (4 + 1)
= 3
2, 3, 6, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Example – Pass 5
2, 3, 6, 7, 9, 9, 11, 12
This pass had only 2
comparisons
This pass no
exchanges are made.
2, 3, 6, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 5
Observation I: The Output of Pass 5 is
We Observe that the Sixth largest among the given 8 elements is placed in the last but Sixth location.
Observation II: For executing the Pass 5 for eight elements we had Two Comparisons
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 5th Pass = 8 – (5 + 1)
= 2
2, 3, 6, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Bubble Sort Example – Pass 6
This pass had only 1
comparison
This pass also had no
exchanges executed.
2, 3, 6, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations of Pass 6
Observation I: The Output of Pass 6 is
We Observe that the Seventh largest among the given 8 elements is placed in the last but Seventh location and
the entire list of eight elements are sorted in ascending order.
Observation II: For executing the Pass 6 for eight elements we had only one Comparison
No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1)
Example:
No. of Comparisons in the 6th Pass = 8 – (6 + 1)
= 1
ie. No. of Comparisons in the ith Pass = n – (i + 1), where n is the no. of elements to be sorted.
2, 3, 6, 7, 9, 9, 11, 12
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
General Observations – Bubble Sort technique
For Sorting n elements we require n-1 Passes of execution
Example: For sorting 8 elements we required 7 passes of execution(Pass 0, Pass 1, Pass 2, … . Pass 6)
No. of Comparisons in the ith Pass = n – (i + 1), where n is the no. of elements to be sorted.
In the algorithmic/Program implementation of Bubble Sort Technique following points to be taken care:
Parent loop signifies the No. of Passes
Sub loop signifies the No. of Comparisons within the ith Pass of execution
Coding section looks like this:
for(i=0;i<n-1;i++)
{
for(j=0;j<n-(i+1);j++)
{
if(num[j] > num [j+1])
{
//Code for swapping num[j] and num[j+1]
}
}
} by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Algorithm: Bubble Sort (A, N):
Given an array A of N elements, this procedure sorts the elements in the ascending order using the method described
above. The variables i and j are used to index the array elements.
• Step 1: For i= 0 toN-1 Do
• Step 2: For j = 0 to N -i - 1 Do
• Step 3:[ Compare adjacent elements ]
If(A[j] >A[j+ l ]) then
[Exchange the values]
temp = A [ j]
A |j ] = A [ j + 1 ]
A [j + 1 ] = temp
End If
• End of Step 2 for loop
• End of Step 1 for loop
Step 4:Exit
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Bubble Sort*/
/* Bubble Sort Technique */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, j, n, temp;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("Enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("nOriginal list of elements before sortingn");
for(i=0;i<n;i++)
printf("%dt",a[i]); by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
//Sorting elements in the array using Bubble Sort technique
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("nSorted listn");
for(i=0;i<n;i++)
printf("%dt",a[i]);
getch();
}
/* End of Program */
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Binary Search:
In this the search element is compared with the middle
element in the list.
If the search element is lesser than the middle element the
binary search is performed again only on the elements to the
left of the middle element.
If the search element is greater than the middle element then
the search is made to the right of middle element.
This process continues until the desired element is found or
the search list becomes empty.
Prof.
Jeo
Joy
A
(Dept.
of
Computer
Science,
Kristu
Jayanti
College(Autonomous)
Bengaluru)
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Algorithm: Binary Search
A is a sorted array with n elements and searchitem is the element to be searched for in the list. low and high
is used to identify the index of first and last element in the range and mid gives the index of middle
element.
Step1: Initialize the variables
low=0, high=n-1,LOC=-1
Step2: while(low<= high)do
mid=(low+high)/2
Step 3: if(searchitem = = A[mid])
LOC=mid
GOTO Step 6
Endif
Step 4:if(searchitem<A[mid])then
high=mid-1
Step 5:else
low=mid+1
Endif
End of while loop
Step 6:if(LOC>=0)then
Display ”searchitem found at position (LOC+1)”
else
Display “searchitem not found”
Endif
Step 7:Exit
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Example:
Consider the elements in array A
11 22 33 44 where n=4
and search element is 11
low = 0(lower bound)
high = 3(upper bound)
mid = (0+3)/2 =1
ITEM<A[mid] so go to the lower half segment.
Therefore reset the value of high to mid-1
low=0 high=0
mid=0
ITEM= =A[0] and search element 11 is found at position 1 (mid+1).
Example:
Consider the search element 77 in the above list 11 22 33 44
low = 0(lower bound)
high = 3(upper bound)
mid = (0+3)/2 =1
A[mid]=22
ITEM>A[mid] so go to the upper half segment.
Therefore reset the value of low to mid+1
low=2 high=3
mid=2
A[mid]=33
ITEM>A[mid] so go to the upper half segment.
Therefore reset the value of low to mid+1
low=3 high=3
mid=3
a[mid]=44
ITEM>A[mid] so go to the upper half segment.
Therefore reset the value of low to mid+1
low=4
Now low>high and therefore conclude that the element is not found
in the list.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*Program to perform Binary Search using iteration*/
#include<stdio.h>
int binary(int[],int,int,int);
void main()
{
int i,j,key,a[20],n,loc=-1,temp;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
//Sort the elements using bubble sort technique
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
loc=binary(a,0,n-1,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
}
//End of main function
/*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);
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
// Recursive implementation of Binary Search Algorithm to return
// the position of target x in the sub-array A[low..high]
#include <stdio.h>
int binarySearch(int A[], int low, int high, int x)
{
int mid;
// Base condition (search space is exhausted)
if (low > high)
return -1;
// we find the mid value in the search space and compares it with target value
mid = (low + high)/2;
// Base condition (target value is found)
if (x == A[mid])
return mid;
// discard all elements in the right search space including the mid element
else if (x < A[mid])
return binarySearch(A, low, mid - 1, x);
// discard all elements in the left search space including the mid element
else
return binarySearch(A, mid + 1, high, x);
}

More Related Content

Similar to Linear Search Swapping Bubble Sort Binary Search.pptx

advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...
Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...
Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...Waqas Tariq
 
PPT.pptx Searching and Sorting Techniques
PPT.pptx Searching and Sorting TechniquesPPT.pptx Searching and Sorting Techniques
PPT.pptx Searching and Sorting TechniquesVaibhav Parjane
 
Unit 2 Searching and Sorting Technique.pptx
Unit 2 Searching and Sorting Technique.pptxUnit 2 Searching and Sorting Technique.pptx
Unit 2 Searching and Sorting Technique.pptxVaibhav Parjane
 
Selection Sort with Improved Asymptotic Time Bounds
Selection Sort with Improved Asymptotic Time BoundsSelection Sort with Improved Asymptotic Time Bounds
Selection Sort with Improved Asymptotic Time Boundstheijes
 
Unit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptxUnit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptxDrYogeshDeshmukh1
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingThenmozhiK5
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxprakashvs7
 
DSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdfDSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdfMustafaJutt4
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptxchouguleamruta24
 
Data Structures Notes
Data Structures NotesData Structures Notes
Data Structures NotesRobinRohit2
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrmsMisssaxena
 

Similar to Linear Search Swapping Bubble Sort Binary Search.pptx (20)

advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
 
Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...
Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...
Bidirectional Bubble Sort Approach to Improving the Performance of Introsort ...
 
PPT.pptx Searching and Sorting Techniques
PPT.pptx Searching and Sorting TechniquesPPT.pptx Searching and Sorting Techniques
PPT.pptx Searching and Sorting Techniques
 
Unit 2 Searching and Sorting Technique.pptx
Unit 2 Searching and Sorting Technique.pptxUnit 2 Searching and Sorting Technique.pptx
Unit 2 Searching and Sorting Technique.pptx
 
Alternate Sort
Alternate SortAlternate Sort
Alternate Sort
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Selection Sort with Improved Asymptotic Time Bounds
Selection Sort with Improved Asymptotic Time BoundsSelection Sort with Improved Asymptotic Time Bounds
Selection Sort with Improved Asymptotic Time Bounds
 
Unit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptxUnit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptx
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
 
DSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdfDSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdf
 
my docoment
my docomentmy docoment
my docoment
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 
Average sort
Average sortAverage sort
Average sort
 
Searching.pptx
Searching.pptxSearching.pptx
Searching.pptx
 
Data Structures Notes
Data Structures NotesData Structures Notes
Data Structures Notes
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrms
 
Sorting
SortingSorting
Sorting
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 

More from JeoJoyA

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptxJeoJoyA
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxJeoJoyA
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxJeoJoyA
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxJeoJoyA
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptxJeoJoyA
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary searchJeoJoyA
 
Linked list
Linked listLinked list
Linked listJeoJoyA
 

More from JeoJoyA (9)

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptx
 
OpenGL
OpenGLOpenGL
OpenGL
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptx
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptx
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary search
 
Linked list
Linked listLinked list
Linked list
 
Tree
TreeTree
Tree
 

Recently uploaded

Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...
Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...
Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...yogeshlabana357357
 
Micropropagation of Madagascar periwinkle (Catharanthus roseus)
Micropropagation of Madagascar periwinkle (Catharanthus roseus)Micropropagation of Madagascar periwinkle (Catharanthus roseus)
Micropropagation of Madagascar periwinkle (Catharanthus roseus)adityawani683
 
GENETICALLY MODIFIED ORGANISM'S PRESENTATION.ppt
GENETICALLY MODIFIED ORGANISM'S PRESENTATION.pptGENETICALLY MODIFIED ORGANISM'S PRESENTATION.ppt
GENETICALLY MODIFIED ORGANISM'S PRESENTATION.pptSyedArifMalki
 
PHOTOSYNTHETIC BACTERIA (OXYGENIC AND ANOXYGENIC)
PHOTOSYNTHETIC BACTERIA  (OXYGENIC AND ANOXYGENIC)PHOTOSYNTHETIC BACTERIA  (OXYGENIC AND ANOXYGENIC)
PHOTOSYNTHETIC BACTERIA (OXYGENIC AND ANOXYGENIC)kushbuR
 
ANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENS
ANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENSANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENS
ANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENSDr. TATHAGAT KHOBRAGADE
 
GBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of AsepsisGBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of AsepsisAreesha Ahmad
 
Electricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 studentsElectricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 studentslevieagacer
 
TEST BANK for Organic Chemistry 6th Edition.pdf
TEST BANK for Organic Chemistry 6th Edition.pdfTEST BANK for Organic Chemistry 6th Edition.pdf
TEST BANK for Organic Chemistry 6th Edition.pdfmarcuskenyatta275
 
Adaptive Restore algorithm & importance Monte Carlo
Adaptive Restore algorithm & importance Monte CarloAdaptive Restore algorithm & importance Monte Carlo
Adaptive Restore algorithm & importance Monte CarloChristian Robert
 
Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...
Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...
Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...Ansari Aashif Raza Mohd Imtiyaz
 
An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...
An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...
An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...NoorulainMehmood1
 
Costs to heap leach gold ore tailings in Karamoja region of Uganda
Costs to heap leach gold ore tailings in Karamoja region of UgandaCosts to heap leach gold ore tailings in Karamoja region of Uganda
Costs to heap leach gold ore tailings in Karamoja region of UgandaTimothyOkuna
 
Terpineol and it's characterization pptx
Terpineol and it's characterization pptxTerpineol and it's characterization pptx
Terpineol and it's characterization pptxMuhammadRazzaq31
 
THE FUNDAMENTAL UNIT OF LIFE CLASS IX.ppt
THE FUNDAMENTAL UNIT OF LIFE CLASS IX.pptTHE FUNDAMENTAL UNIT OF LIFE CLASS IX.ppt
THE FUNDAMENTAL UNIT OF LIFE CLASS IX.pptsinghnarendra5386
 
Factor Causing low production and physiology of mamary Gland
Factor Causing low production and physiology of mamary GlandFactor Causing low production and physiology of mamary Gland
Factor Causing low production and physiology of mamary GlandRcvets
 
Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...
Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...
Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...kevin8smith
 
EU START PROJECT. START-Newsletter_Issue_4.pdf
EU START PROJECT. START-Newsletter_Issue_4.pdfEU START PROJECT. START-Newsletter_Issue_4.pdf
EU START PROJECT. START-Newsletter_Issue_4.pdfStart Project
 
GBSN - Biochemistry (Unit 3) Metabolism
GBSN - Biochemistry (Unit 3) MetabolismGBSN - Biochemistry (Unit 3) Metabolism
GBSN - Biochemistry (Unit 3) MetabolismAreesha Ahmad
 
GBSN - Microbiology (Unit 5) Concept of isolation
GBSN - Microbiology (Unit 5) Concept of isolationGBSN - Microbiology (Unit 5) Concept of isolation
GBSN - Microbiology (Unit 5) Concept of isolationAreesha Ahmad
 

Recently uploaded (20)

Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...
Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...
Soil and Water Conservation Engineering (SWCE) is a specialized field of stud...
 
Micropropagation of Madagascar periwinkle (Catharanthus roseus)
Micropropagation of Madagascar periwinkle (Catharanthus roseus)Micropropagation of Madagascar periwinkle (Catharanthus roseus)
Micropropagation of Madagascar periwinkle (Catharanthus roseus)
 
GENETICALLY MODIFIED ORGANISM'S PRESENTATION.ppt
GENETICALLY MODIFIED ORGANISM'S PRESENTATION.pptGENETICALLY MODIFIED ORGANISM'S PRESENTATION.ppt
GENETICALLY MODIFIED ORGANISM'S PRESENTATION.ppt
 
PHOTOSYNTHETIC BACTERIA (OXYGENIC AND ANOXYGENIC)
PHOTOSYNTHETIC BACTERIA  (OXYGENIC AND ANOXYGENIC)PHOTOSYNTHETIC BACTERIA  (OXYGENIC AND ANOXYGENIC)
PHOTOSYNTHETIC BACTERIA (OXYGENIC AND ANOXYGENIC)
 
ANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENS
ANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENSANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENS
ANITINUTRITION FACTOR GYLCOSIDES SAPONINS CYANODENS
 
GBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of AsepsisGBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of Asepsis
 
Electricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 studentsElectricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 students
 
TEST BANK for Organic Chemistry 6th Edition.pdf
TEST BANK for Organic Chemistry 6th Edition.pdfTEST BANK for Organic Chemistry 6th Edition.pdf
TEST BANK for Organic Chemistry 6th Edition.pdf
 
HIV AND INFULENZA VIRUS PPT HIV PPT INFULENZA VIRUS PPT
HIV AND INFULENZA VIRUS PPT HIV PPT  INFULENZA VIRUS PPTHIV AND INFULENZA VIRUS PPT HIV PPT  INFULENZA VIRUS PPT
HIV AND INFULENZA VIRUS PPT HIV PPT INFULENZA VIRUS PPT
 
Adaptive Restore algorithm & importance Monte Carlo
Adaptive Restore algorithm & importance Monte CarloAdaptive Restore algorithm & importance Monte Carlo
Adaptive Restore algorithm & importance Monte Carlo
 
Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...
Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...
Molecular and Cellular Mechanism of Action of Hormones such as Growth Hormone...
 
An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...
An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...
An Overview of Active and Passive Targeting Strategies to Improve the Nano-Ca...
 
Costs to heap leach gold ore tailings in Karamoja region of Uganda
Costs to heap leach gold ore tailings in Karamoja region of UgandaCosts to heap leach gold ore tailings in Karamoja region of Uganda
Costs to heap leach gold ore tailings in Karamoja region of Uganda
 
Terpineol and it's characterization pptx
Terpineol and it's characterization pptxTerpineol and it's characterization pptx
Terpineol and it's characterization pptx
 
THE FUNDAMENTAL UNIT OF LIFE CLASS IX.ppt
THE FUNDAMENTAL UNIT OF LIFE CLASS IX.pptTHE FUNDAMENTAL UNIT OF LIFE CLASS IX.ppt
THE FUNDAMENTAL UNIT OF LIFE CLASS IX.ppt
 
Factor Causing low production and physiology of mamary Gland
Factor Causing low production and physiology of mamary GlandFactor Causing low production and physiology of mamary Gland
Factor Causing low production and physiology of mamary Gland
 
Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...
Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...
Harry Coumnas Thinks That Human Teleportation is Possible in Quantum Mechanic...
 
EU START PROJECT. START-Newsletter_Issue_4.pdf
EU START PROJECT. START-Newsletter_Issue_4.pdfEU START PROJECT. START-Newsletter_Issue_4.pdf
EU START PROJECT. START-Newsletter_Issue_4.pdf
 
GBSN - Biochemistry (Unit 3) Metabolism
GBSN - Biochemistry (Unit 3) MetabolismGBSN - Biochemistry (Unit 3) Metabolism
GBSN - Biochemistry (Unit 3) Metabolism
 
GBSN - Microbiology (Unit 5) Concept of isolation
GBSN - Microbiology (Unit 5) Concept of isolationGBSN - Microbiology (Unit 5) Concept of isolation
GBSN - Microbiology (Unit 5) Concept of isolation
 

Linear Search Swapping Bubble Sort Binary Search.pptx

  • 1. SEARCHING • Searching refers to the operation of finding the location of a given search item in the given collection of items. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 2. Linear Search or Sequential search The most straight forward method of finding a particular element in an unordered list is linear search. This technique simply involves the comparison of each element of the list in a sequential manner until the desired element is found. Algorithm: Linear Search 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 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 3. 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 incremnt i, and i=1 A[i]=11 11!= 99 incremnt i, and i=2 A[2] =66 66!=99 incremnt i, and i=3 A[3] =44 44!=99 incremnt i, and i=4 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 4. /*Program to perform Linear Search using iteration*/ #include<stdio.h> int linear(int[],int,int); void main() { int i,key,a[20],n,loc=-1; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("Enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=linear(a,n,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 5. /*Program to perform Linear Search using iteration*/ #include<stdio.h> int linear(int[],int,int); void main() { int i,key,a[20],n,loc=-1; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("Enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=linear(a,n,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 6. /*Program to perform Linear Search using iteration*/ /*Linear search iterative function*/ int linear(int a[10],int n,int search) { int i; for(i=0;i<n;i++) { if(a[i]==search) return(i); } return(-1); } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 7. /*Program to perform Linear Search using iteration*/ /*Linear search iterative function*/ int linear(int a[10],int n,int search) { int i; for(i=0;i<n;i++) { if(a[i]==search) return(i); } return(-1); } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 8. /*Program to perform Linear Search using iteration*/ Output: Enter the number of elements 3 Enter the elements 33 21 19 Enter the search element 21 Element found at 2 position by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 9. /*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 elementsn"); scanf("%d",&n); printf("enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=linear(a,n,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 10. /*Linear search recursive function*/ int linear(int a[10],int n,int search) { if(n<0) return(-1); else if(a[n-1]==search) return(n-1); else return(linear(a,n-1,search)); } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 11. Complexity of linear search The complexity of the algorithm is measured by the number of comparisons f(n) required to find the search element ITEM in the array A consisting of n elements. The worst case occurs when we search through the entire array A and ITEM does not appear in A. In this case algorithm requires f(n)= n+1 comparisons Thus in the worst case f(n) is proportional to n The number of comparisons in the average case can be any number 1,2,…. N and each number occurs with probability P=1/n. then f (n) = 1.1/n + 2.1/n + ….. n. 1/n = (1+2+……n). 1/n = n(n+1)/2. 1/n = (n+1)/2 Hence f(n) in the average case is approximately equal to half the number of elements in the list. In the best case the element can be found in the first comparison itself where f(n)=1. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 12. Swapping and Bubble Sort Technique by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 13. Swapping: Exchange the contents G1 G2 Initially (before swapping) G1: Filled with water G2: Filled with Milk by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 14. After Swapping G1 G2 After swapping G1: Filled with Milk G2: Filled with Water How it happened? After Swapping operation G1: Should be filled with the contents of G2(Milk) G2: Should be filled with the contents of G1(Water) by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 15. How Swapping happened Take an empty glass G3 of same or higher capacity Step 1: Pour contents of G1 (Water) to the Empty Glass G3 Then G1 will be empty and G3 will have water G3 G1 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 16. Step 2: Pour contents of G2 (Milk) to the Empty Glass G1 Then G2 will be empty and G1 will have Milk G1 G2 After swapping G1: Filled with Milk G2: Filled with Water by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 17. Step 3: Pour contents of G3 (Water) to the Empty Glass G2 Then G3 will be empty and G2 will have Water G2 G3 After swapping G1: Filled with Milk G2: Filled with Water by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 18. // Program to swap the contents of two integer variables #include<stdio.h> void main() { int i=2,j=3,temp; clrscr(); printf(“n Before Swapping: i = %d t j = %d”,i,j); temp = i; i = j; j = temp Printf(“n After Swapping: i = %d t j = %d”,i,j); getch(); }//End of Program by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 19. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru •Sorting • Sorting refers to the operation of arranging the given data items in a specified order either ascending or descending. Sorting can be classified as • Internal sorting – Sorting the records that are stored are in main memory. • External sorting – records that are sorted are in auxiliary storage. There are many methods of sorting; some of them are • Bubble sort • Insertion sort • Selection sort • Merge sort • Quick sort • Heap sort
  • 20. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Efficiency parameters: The sorting method that is to be implemented depends on how it behaves in each situation. For a given problem, it is important to know which method will be best suited. Some parameters studied are: 1. Execution time 2. Space or Memory 3. Coding time • Execution time It is the time required for the execution of the program. This time required is more if there are more number of comparisons and exchanges of data. • Space or memory It is the amount of space required to store data. • Coding time It is the time required to develop a sorting technique for the given problem. It depends on the complexity of the algorithm.
  • 21. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Complexity function f(n): Complexity function f(n) is the function which gives the running time of the algorithm in terms of size of the input data ‘n’. There are three cases for finding the complexity function f(n). 1. Worst case In this, maximum number of comparisons are made or maximum value of f(n) is determined. 2. Average case Average number of comparisons are made or average value of f(n) is determined. 3. Best case Minimum number of comparisons are made or minimum value of f(n) is determined.
  • 22. Bubble Sort by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 23. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Bubble Sort Technique It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order (the first element is larger than the second element). The algorithm gets its name from the way LARGER elements "bubble" to the top of the list.
  • 24. Bubble Sort Example – Pass 0 9, 6, 2, 12, 11, 9, 3, 7 6, 9, 2, 12, 11, 9, 3, 7 6, 2, 9, 12, 11, 9, 3, 7 6, 2, 9, 12, 11, 9, 3, 7 6, 2, 9, 11, 12, 9, 3, 7 6, 2, 9, 11, 9, 12, 3, 7 6, 2, 9, 11, 9, 3, 12, 7 6, 2, 9, 11, 9, 3, 7, 12 The 12 is greater than the 7 so they are exchanged. The 12 is greater than the 3 so they are exchanged. The twelve is greater than the 9 so they are exchanged The 12 is larger than the 11 so they are exchanged. In the third comparison, the 9 is not larger than the 12 so no exchange is made. We move on to compare the next pair without any change to the list. Now the next pair of numbers are compared. Again the 9 is the larger and so this pair is also exchanged. Bubblesort compares the numbers in pairs from left to right exchanging when necessary. Here the first number 9 is compared to the second 6 and as it is larger they are exchanged. The end of the list has been reached so this is the end of the first pass. The twelve at the end of the list must be largest number in the list and so is now in the correct position. We now start a new pass from left to right. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 25. Observations of Pass 0 Observation I: The Output of Pass 0 is We Observe that the largest among the given 8 elements is placed in the last location. Observation II: For executing the Pass 0 for eight elements we had Seven Comparisons No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 0th Pass = 8 – (0 + 1) = 7 6, 2, 9, 11, 9, 3, 7, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 26. Bubble Sort Example – Pass 1 6, 2, 9, 11, 9, 3, 7, 12 2, 6, 9, 11, 9, 3, 7, 12 2, 6, 9, 9, 11, 3, 7, 12 2, 6, 9, 9, 3, 11, 7, 12 2, 6, 9, 9, 3, 7, 11, 12 Notice that this time we do not have to compare the last two numbers as we know the 12 is in position. This pass therefore only requires 6 comparisons. 2, 6, 9, 11, 9, 3, 7, 12 2, 6, 9, 11, 9, 3, 7, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 27. Observations of Pass 1 Observation I: The Output of Pass 1 is We Observe that the Second largest among the given 8 elements is placed in the penultimate (second last) location. Observation II: For executing the Pass 1 for eight elements we had Six Comparisons No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 1st Pass = 8 – (1 + 1) = 6 2, 6, 9, 9, 3, 7, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 28. Bubble Sort Example – Pass 2 2, 6, 9, 9, 3, 7, 11, 12 2, 6, 9, 3, 9, 7, 11, 12 2, 6, 9, 9, 3, 7, 11, 12 This time the 11 and 12 are in position. This pass therefore only requires 5 comparisons. 2, 6, 9, 9, 3, 7, 11, 12 2, 6, 9, 9, 3, 7, 11, 12 2, 6, 9, 3, 7, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 29. Observations of Pass 2 Observation I: The Output of Pass 2 is We Observe that the Third largest among the given 8 elements is placed in the last third location. Observation II: For executing the Pass 2 for eight elements we had Five Comparisons No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 2nd Pass = 8 – (2 + 1) = 5 2, 6, 9, 3, 7, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 30. Bubble Sort Example – Pass 3 2, 6, 9, 3, 7, 9, 11, 12 2, 6, 3, 9, 7, 9, 11, 12 2, 6, 3, 7, 9, 9, 11, 12 Each pass requires fewer comparisons. This time only 4 are needed. 2, 6, 9, 3, 7, 9, 11, 12 2, 6, 9, 3, 7, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 31. Observations of Pass 3 Observation I: The Output of Pass 3 is We Observe that the Fourth largest among the given 8 elements is placed in the last but fourth location. Observation II: For executing the Pass 3 for eight elements we had Four Comparisons No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 3rd Pass = 8 – (3 + 1) = 4 2, 6, 3, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 32. Bubble Sort Example – Pass 4 2, 6, 3, 7, 9, 9, 11, 12 2, 3, 6, 7, 9, 9, 11, 12 This pass uses 3 comparisons. The list is now sorted but the algorithm does not know this until it completes a pass with no exchanges. 2, 6, 3, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 33. Observations of Pass 4 Observation I: The Output of Pass 4 is We Observe that the Fifth largest among the given 8 elements is placed in the last but fifth location. Observation II: For executing the Pass 4 for eight elements we had Three Comparisons No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 4th Pass = 8 – (4 + 1) = 3 2, 3, 6, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 34. Bubble Sort Example – Pass 5 2, 3, 6, 7, 9, 9, 11, 12 This pass had only 2 comparisons This pass no exchanges are made. 2, 3, 6, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 35. Observations of Pass 5 Observation I: The Output of Pass 5 is We Observe that the Sixth largest among the given 8 elements is placed in the last but Sixth location. Observation II: For executing the Pass 5 for eight elements we had Two Comparisons No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 5th Pass = 8 – (5 + 1) = 2 2, 3, 6, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 36. Bubble Sort Example – Pass 6 This pass had only 1 comparison This pass also had no exchanges executed. 2, 3, 6, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 37. Observations of Pass 6 Observation I: The Output of Pass 6 is We Observe that the Seventh largest among the given 8 elements is placed in the last but Seventh location and the entire list of eight elements are sorted in ascending order. Observation II: For executing the Pass 6 for eight elements we had only one Comparison No. of Comparisons in a Pass = No. of elements to be sorted – (Pass No. + 1) Example: No. of Comparisons in the 6th Pass = 8 – (6 + 1) = 1 ie. No. of Comparisons in the ith Pass = n – (i + 1), where n is the no. of elements to be sorted. 2, 3, 6, 7, 9, 9, 11, 12 by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 38. General Observations – Bubble Sort technique For Sorting n elements we require n-1 Passes of execution Example: For sorting 8 elements we required 7 passes of execution(Pass 0, Pass 1, Pass 2, … . Pass 6) No. of Comparisons in the ith Pass = n – (i + 1), where n is the no. of elements to be sorted. In the algorithmic/Program implementation of Bubble Sort Technique following points to be taken care: Parent loop signifies the No. of Passes Sub loop signifies the No. of Comparisons within the ith Pass of execution Coding section looks like this: for(i=0;i<n-1;i++) { for(j=0;j<n-(i+1);j++) { if(num[j] > num [j+1]) { //Code for swapping num[j] and num[j+1] } } } by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 39. Algorithm: Bubble Sort (A, N): Given an array A of N elements, this procedure sorts the elements in the ascending order using the method described above. The variables i and j are used to index the array elements. • Step 1: For i= 0 toN-1 Do • Step 2: For j = 0 to N -i - 1 Do • Step 3:[ Compare adjacent elements ] If(A[j] >A[j+ l ]) then [Exchange the values] temp = A [ j] A |j ] = A [ j + 1 ] A [j + 1 ] = temp End If • End of Step 2 for loop • End of Step 1 for loop Step 4:Exit by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 40. /*Program to perform Bubble Sort*/ /* Bubble Sort Technique */ #include<stdio.h> #include<conio.h> void main() { int a[20], i, j, n, temp; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("Enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("nOriginal list of elements before sortingn"); for(i=0;i<n;i++) printf("%dt",a[i]); by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 41. //Sorting elements in the array using Bubble Sort technique for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("nSorted listn"); for(i=0;i<n;i++) printf("%dt",a[i]); getch(); } /* End of Program */ by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 42. Binary Search: In this the search element is compared with the middle element in the list. If the search element is lesser than the middle element the binary search is performed again only on the elements to the left of the middle element. If the search element is greater than the middle element then the search is made to the right of middle element. This process continues until the desired element is found or the search list becomes empty. Prof. Jeo Joy A (Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru) by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 43. Algorithm: Binary Search A is a sorted array with n elements and searchitem is the element to be searched for in the list. low and high is used to identify the index of first and last element in the range and mid gives the index of middle element. Step1: Initialize the variables low=0, high=n-1,LOC=-1 Step2: while(low<= high)do mid=(low+high)/2 Step 3: if(searchitem = = A[mid]) LOC=mid GOTO Step 6 Endif Step 4:if(searchitem<A[mid])then high=mid-1 Step 5:else low=mid+1 Endif End of while loop Step 6:if(LOC>=0)then Display ”searchitem found at position (LOC+1)” else Display “searchitem not found” Endif Step 7:Exit by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 44. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Example: Consider the elements in array A 11 22 33 44 where n=4 and search element is 11 low = 0(lower bound) high = 3(upper bound) mid = (0+3)/2 =1 ITEM<A[mid] so go to the lower half segment. Therefore reset the value of high to mid-1 low=0 high=0 mid=0 ITEM= =A[0] and search element 11 is found at position 1 (mid+1). Example: Consider the search element 77 in the above list 11 22 33 44 low = 0(lower bound) high = 3(upper bound) mid = (0+3)/2 =1 A[mid]=22 ITEM>A[mid] so go to the upper half segment. Therefore reset the value of low to mid+1 low=2 high=3 mid=2 A[mid]=33 ITEM>A[mid] so go to the upper half segment. Therefore reset the value of low to mid+1 low=3 high=3 mid=3 a[mid]=44 ITEM>A[mid] so go to the upper half segment. Therefore reset the value of low to mid+1 low=4 Now low>high and therefore conclude that the element is not found in the list.
  • 45. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru /*Program to perform Binary Search using iteration*/ #include<stdio.h> int binary(int[],int,int,int); void main() { int i,j,key,a[20],n,loc=-1,temp; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); //Sort the elements using bubble sort technique for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } loc=binary(a,0,n-1,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); } //End of main function /*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); }
  • 46. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru // Recursive implementation of Binary Search Algorithm to return // the position of target x in the sub-array A[low..high] #include <stdio.h> int binarySearch(int A[], int low, int high, int x) { int mid; // Base condition (search space is exhausted) if (low > high) return -1; // we find the mid value in the search space and compares it with target value mid = (low + high)/2; // Base condition (target value is found) if (x == A[mid]) return mid; // discard all elements in the right search space including the mid element else if (x < A[mid]) return binarySearch(A, low, mid - 1, x); // discard all elements in the left search space including the mid element else return binarySearch(A, mid + 1, high, x); }