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

Module 5 Basic Algorithm

Module 5 covers basic algorithms including definitions and criteria for algorithms, searching techniques like Linear and Binary Search, and sorting methods such as Bubble Sort, Insertion Sort, and Selection Sort. Each algorithm is explained with its working principles, advantages, and disadvantages, alongside example codes in C. The document emphasizes the importance of sorting and searching in data structures for efficient data management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Module 5 Basic Algorithm

Module 5 covers basic algorithms including definitions and criteria for algorithms, searching techniques like Linear and Binary Search, and sorting methods such as Bubble Sort, Insertion Sort, and Selection Sort. Each algorithm is explained with its working principles, advantages, and disadvantages, alongside example codes in C. The document emphasizes the importance of sorting and searching in data structures for efficient data management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

MODULE 5: (BASIC ALGORITHMS)

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

1. Input: Zero or more quantities are externally supplied.


2. Output: At least one quantity is produced.
3. Definiteness: Each instruction is clear and unambiguous.
4. Finiteness: Algorithm should terminate after finite number of steps.
5. Effectiveness: Every instruction must be basic i.e., it can be carried out in finite length of
time in an effective manner.

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.

Eg: consider the following Array A

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:

LINEAR(DATA, N,ITEM, LOC)

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.

Step 1: Set DATA[N+1]=ITEM


Step 2: Set LOC=1
Step 3: Repeat while (DATA [LOC] != ITEM) Set LOC=LOC+1
Step 4: if LOC=N+1 then Set LOC= -1.
Step 5: Exit
Program for linear search:
// Linear Search in C
#include <stdio.h>
#include<conio.h>
void main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}}
if (c == n)
printf("%d isn't present in the array.\n", search);
getch();
}
Advantages:
 It is simplest known technique.
 The elements in the list can be in any order.
Disadvantages:
This method is in efficient when large numbers of elements are present in list because time taken for
searching is more.

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.

ALGORITHM: BINARY SEARCH[A,N,KEY]


Step 1: begin
Step 2: [Initilization] Lb=1; ub=n;
Step 3: [Search for the ITEM] Repeat through step 4,while Lower bound is less than Upper Bound.
Step 4: [Obtain the index of middle value]
MID=(lb+ub)/2
Step 5: [Compare to search for ITEM]
If KeyA[MID] then Lb=MID+1
Otherwise write “Match Found”
Return Middle.
Step 6: [Unsuccessful Search]
write “Match Not Found”
Step 7: Stop
Program for Binary search:
#include <stdio.h>
void main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
getch();
}

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

First half of the array should be determined by using formula


mid=[lb+ub]/2
Here mid = [0 + 9] / 2 = 4.5. take 4 as mid of the array.
Now we compare the value stored at location 4, with the value being searched, 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 of the array. Now change
lb to mid + 1 and find the new mid value again.
lb= mid +1;
again mid= [5+9]/2 = 7
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31. The
value stored at location 7 is not a match, rather it is more than what we are looking for. So, the
value must be in the lower part from this location. we calculate the mid again. This time it is 5. We
compare the value stored at location 5 with our target value. We find that it is a match. We
conclude that the target value 31 is stored at location 5.
SORTING: Sorting is a technique of organizing data. It is a process of arranging the elements either may
be ascending or descending order, ie; bringing some order lines with data. Sorting can be performed on any
one or combination of one or more attributes present in each record. It is very easy and efficient to perform
searching, if data is stored in sorting order. The sorting is performed according to the key value of each
record. Depending up on the makeup of key, records can be stored either numerically or alphanumerically.
In numerical sorting, the records arranged in ascending or descending order according to the numeric value
of the key.

Types of Sorting Techniques: Sorting techniques are categorized into 2 types.


1. Internal Sorting
2. External Sorting
S.N Internal Sorting External sorting
1 Internal Sorting takes place in the main External sorting is done with additional external
memory of a computer memory like magnetic tape or hard disk
2 The internal sorting methods are applied The External sorting methods are applied only
to small collection of data. when the number of data elements to be sorted is
too large.
3 Internal sorting does not make use of External sorting make use of extra resources.
extra resources.
4 Example of Internal Sorting algorithms Example of External sorting algorithms are: -
are :- Bubble Sort, Internal Sort, Quick Merge Sort, Two-way merge sort.
Sort, Heap Sort, Binary Sort, Radix Sort,
Selection sort.

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 )

Step 1 : Repeat For P = 1 to N – 1 Begin

Step 2 : Repeat For J = 1 to N – P Begin

Step 3 : If ( A [ J ] < A [ J – 1 ] ) Swap ( A [ J ] , A [ J – 1 ] ) End For

End For

Step 4 : Exit
Program:

/* bubble sort implementation */


#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,temp,j,arr[25];
clrscr();
printf("Enter the number of elements in the Array: ");
scanf("%d",&n);
printf("\nEnter the elements:\n\n");
for(i=0 ; i<n;i++)
{
printf(" Array[%d] = ",i);
scanf("%d",&arr[i]);
}
for(i=0 ; i<n;i++)
{
for(j=0 ; j<n;j++)
{
if(arr[j]>arr[j+1]) //Swapping Condition is Checked
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}}}
printf("\nThe Sorted Array is:\n\n");
for(i=0 ; i<n;i++)
{
printf(" %4d",arr[i]);
}
getch();
}

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:

Working of Insertion Sort:

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}.

Pass Pos A[0] A[1] A[2] A[3] A[4] A[5]


1 1 2 10 3 90 43 56
2 2 2 3 10 90 43 56
3 3 2 3 10 90 43 56
4 4 2 3 10 43 90 56
5 5 2 3 10 43 56 90

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 ();
}

You might also like