Module 5 Basic Algorithm
Module 5 Basic Algorithm
ALGORITHM: Algorithm is a finite set of instructions that, if followed accomplishes a particular task. An
algorithm is given an initial state, proceed through a well-defined series of successive states and terminating
in an end state. Algorithm should satisfy the following criteria
Searching: Searching is an operation or a technique that helps finds the place of a given element or value in
the list. Any search is said to be successful or unsuccessful depending upon whether the element that is
being searched is found or not. Some of the standard searching technique that is being followed in data
structure is listed below:
1. Linear Search
2. Binary Search
LINEAR SEARCH: an element or value in a given array by traversing the array from the starting, till the
desired element or value is found. It compares the element to be searched with all the elements present in
the array and when the element is matched successfully, it returns the index of the element in the array, else
it return -1. Linear Search is applied on unsorted or unordered lists, when there are fewer elements in a list.
Linear search is also called as sequential search.
23 15 18 17 42 96 103
Now let us search for 17 by Linear search. The searching starts from the first position. The above process
continues until the search element is found.
Algorithm:
Here DATA is a linear Array with N elements. And ITEM is a given item of information. This algorithm
finds the location LOC of an ITEM in DATA. LOC=-1 if the search is unsuccessful.
BINARY SEARCH:
Binary Search is used with sorted array or list. Binary Search is useful when there are large number of
elements in an array and they are sorted. So a necessary condition for Binary search to work is that the
list/array should be sorted. Binary search is a fast search algorithm. This search algorithm works on the
principle of divide and conquers. The algorithm compares ITEM with middle element.
mid=[lb+ub]/2.(where lb= Lower bound & ub= upper bond)
In binary search, we follow the following steps:
1. We start by comparing the element to be searched with the element in the middle of the list/array.
2. If we get a match, we return the index of the middle element.
3. If we do not get a match, we check whether the element to be searched is less or greater than in
value than the middle element.
4. If the element/number to be searched is greater in value than the middle number, then we pick the
elements on the right side of the middle element(as the list/array is sorted, hence on the right, we
will have all the numbers greater than the middle number), and start again from the step 1.
5. If the element/number to be searched is lesser in value than the middle number, then we pick the
elements on the left side of the middle element, and start again from the step 1.
Example:
let us assume that we need to search the location of value 31 using binary search.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
THE BUBBLE SORT: The bubble sort makes multiple passes through a list. It compares adjacent items
and exchanges those that are out of order. Each pass through the list places the next largest value in its
proper place.
Working of Bubble Sort
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
a. Starting from the first index, compare the first and the second elements.
b. If the first element is greater than the second element, they are swapped.
c. Now, compare the second and the third elements. Swap them if they are not in order.
d. The above process goes on until the last element
2. Remaining Iteration:
The same process goes on for the remaining iterations. After each iteration, the largest element among the
unsorted elements is placed at the end.
Algorithm: Bubble_Sort ( A [ ] , N )
End For
Step 4 : Exit
Program:
Example:
THE INSERTION SORT:
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration. In
insertion sort the element is inserted at an appropriate place similar to card insertion. Here the list is divided
into two parts sorted and unsorted sub-lists. In each pass, the first element of unsorted sub list is picked up
and moved into the sorted sub list by inserting it in suitable position. Suppose we have „n‟ elements, we
need n-1 passes to sort the elements. Insertion sort works this way:
1. The first element in the array is assumed to be sorted. Take the second element and store it
separately in key. Compare key with the first element. If the first element is greater than key, then
key is placed in front of the first element.
2. Now, the first two elements are sorted. Take the third element and compare it with the elements on
the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it,
then place it at the beginning of the array.
3. Similarly, place every unsorted element at its correct position.
Example:
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10],i,j,k,n;
clrscr( );
printf("How many elements you want to sort?\n");
scanf("%d",&n);
printf("\nEnter the Elements into an array:\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
for(j= i-1; j>=0 && k<a[j]; j--)
a[j+1]=a[j];
a[j+1]=k;
} printf("\n\n Elements after sorting: \n");
for(i=0;i<n;i++)
printf("%d\n", a[i]);
getch( );
}
OUTPUT:
How many elements you want to sort ? : 6
Enter elements for an array : 78 23 45 8 32 36
After Sorting the elements are : 8 23 32 36 45 78
THE SELECTION SORT:
In selection sort, the smallest value among the unsorted elements of the array is selected in every
pass and inserted to its appropriate position into the array. First, find the smallest element of the
array and place it on the first position. Then, find the second smallest element of the array and place
it on the second position. The process continues until we get the sorted array. The array with n
elements is sorted by using n-1 pass of selection sort algorithm.
In 1st pass, smallest element of the array is to be found along with its index pos. then, swap
A[0] and A[pos]. Thus A[0] is sorted, we now have n -1 elements which are to be sorted.
In 2nd pas, position pos of the smallest element present in the sub-array A[n1] is found. Then,
swap, A[1] and A[pos]. Thus A[0] and A[1] are sorted, we now left with n-2 unsorted elements.
In n-1th pass, position pos of the smaller element between A[n-1] and A[n-2] is to be found.
Then, swap, A[pos] and A[n-1].
Therefore, by following the above explained process, the elements A[0], A[1], A[2], …….... , A[n-
1] are sorted.
Example: Consider the following array with 6 elements. Sort the elements of the array by using
selection sort. A = {10, 2, 3, 90, 43, 56}.
Algorithm:
Program:
/* program to sort elements of an array using selection sort*/
#include<stdio.h>
void main( )
{
int i,j,t,n,min,a[10];
clrscr( );
printf("\n How many elements you want to sort? ");
scanf("%d",&n);
printf("\Enter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
if(a[j] > a[min])
{
min=j;
}
t=a[i];
a[i]=a[min];
a[min]=t;
} printf("\nAfter sorting the elements are:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch( );
}
Algorithm to find all the roots of a quadratic equation:
Step 1: Start
Step 2: Read a, b, c values
Step 3: Compute d = b2 4ac
Step 4: if d > 0 then
r1 = b+ sqrt (d)/(2*a)
r2 = b sqrt(d)/(2*a)
Step 5: Otherwise if d = 0 then
compute r1 = -b/2a, r2=-b/2a
print r1,r2 values
Step 6: Otherwise if d < 0 then print roots are imaginary
Step 7: Stop
Program:
# include<stdio.h>
# include<conio.h>
# include<math.h>
Void main (){
float a,b,c,r1,r2,d;
printf (“enter the values of a b c”);
scanf (“ %f %f %f”, &a, &b, &c);
d= b*b – 4*a*c;
if (d>0){
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf (“The real roots = %f %f”, r1, r2);
}
else if (d= =0){
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (“roots are equal =%f %f”, r1, r2);
}
else
printf(“Roots are imaginary”);
getch ();
}