Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
DIVYA SHARMA
ROLL-NO : SG-16846
EXP 1:- INTRODUCTION
DAA – Introduction
An algorithm is the best way to represent the solution of a particular problem in a very
simple and efficient way. If we have an algorithm for a specific problem, then we can
implement it in any programming language, meaning that the algorithm is independent
from any programming languages.
Algorithm Design
The important aspects of algorithm design include creating an efficient algorithm to solve a
problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient
with respect to time consumption, whereas other approaches may be memory efficient.
However, one has to keep in mind that both time consumption and memory usage cannot be
optimized simultaneously. If we require an algorithm to run in lesser time, we have to invest
in more memory and if we require an algorithm to run with lesser memory, we need to have
more time.
1. Problem definition
2. Development of a model
3. Specification of an Algorithm
4. Designing an Algorithm
5. Checking the correctness of an Algorithm
6. Analysis of an Algorithm
7. Implementation of an Algorithm
8. Program testing
9. Documentation
10.
Characteristics of Algorithms
4. Algorithms halt in a finite amount of time. Algorithms should not run for infinity,
i.e., an algorithm must end at some point.
EXPERIMENT:2
Linked list:
A linked list is a linear data structure, in which the elements are not stored at contiguous
memory locations. The elements in a linked list are linked using pointers as shown in the
below image:
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
printList(head);
return 0;
}
Output
EXPERIMENT:3
Stack:
A stack is a container of objects that are inserted and removed according to the last-in first-
out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the item
into the stack, and pop the item out of the stack. A stack is a limited access data structure -
elements can be added and removed from the stack only at the top. push adds an item to the
top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack
of books; you can remove only the top book, also you can add a new book on the top.
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
Output
EXPERIMENT:4
QUEUE
A Queue is a linear structure which follows a particular order in which the operations are
performed. The order is First In First Out (FIFO). A good example of a queue is any queue of
consumers for a resource where the consumer that came first is served first. The difference
between stacks and queues is in removing. In a stack we remove the item the most recently
added; in a queue, we remove the item the least recently added.
#include<conio.h>
void Insert() {
int val;
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else {
if (front == - 1)
front = 0;
cin>>val;
rear++;
queue[rear] = val;
}
}
void Delete() {
return ;
} else {
front++;;
void Display() {
if (front == - 1)
cout<<"Queue is empty"<<endl;
else {
cout<<queue[i]<<" ";
cout<<endl;
int main() {
int ch;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin<<ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
} while(ch!=4);
return 0;
Output
EXPERIMENT:5
Quicksort:
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot
and partitions the given array around the picked pivot. There are many different versions of
quickSort that pick pivot in different ways.
11. Always pick first element as pivot.
12. Always pick last element as pivot (implemented below)
13. Pick a random element as pivot.
14. Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x. All
this should be done in linear time.
return 0;
}
Output
EXPERIMENT:6
Merge Sort:
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two
halves, calls itself for the two halves and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes
that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See
following C implementation for details.
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
Call mergeSort(arr, l, m)
Call merge(arr, l, m, r)
The following diagram from wikipedia shows the complete merge sort process for an
example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see
that the array is recursively divided in two halves till the size becomes 1. Once the size
becomes 1, the merge processes comes into action and starts merging arrays back till the
complete array is merged.
Program to implement merge sort:
#include <stdio.h>
#include<conio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
void merging(int low, int mid, int high) {
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high) {
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
}
else
{
return;
}
}
int main() {
int i;
printf("List before sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}
Output
EXPERIMENT:7
Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.
Algorithm:
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
#include<stdio.h>
#include<conio.h>
int main()
{
int a[20],i,x,n;
clrscr();
printf("How many elements?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("Element found at index %d",i);
break;
}
if(a[i]!=x)
{
if(i==n-1)
{
printf("Element Not Found");
}
}
getch();
return 0;
}
Output
EXPERIMENT:8
Binary search
C program for binary search: This code implements binary search in C language. It can only
be used for sorted arrays, but it's fast as compared to linear search. If you wish to use binary
search on an array which isn't sorted, then you must sort it using some sorting technique say
merge sort and then use the binary search algorithm to find the desired element in the list. If
the element to be searched is found then its position is printed. The code below assumes that
the input numbers are in ascending order.
#include <stdio.h>
#include<conio.h>
int main()
scanf("%d",&n);
scanf("%d",&array[c]);
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
first = middle + 1;
break;
else
last = middle - 1;
return 0;
Output
Experiment:9
The Greedy algorithm could be understood very well with a well-known problem referred to
as Knapsack problem. Although the same problem could be solved by employing other
algorithmic approaches, Greedy approach solves Fractional Knapsack problem reasonably in
a good time. Let us discuss the Knapsack problem in detail.
Knapsack Problem
Given a set of items, each with a weight and a value, determine a subset of items to include in
a collection so that the total weight is less than or equal to a given limit and the total value is
as large as possible.
The knapsack problem is in combinatorial optimization problem. It appears as a subproblem
in many, more complex mathematical models of real-world problems. One general approach
to difficult problems is to identify the most restrictive constraint, ignore the others, solve a
knapsack problem, and somehow adjust the solution to satisfy the ignored constraints.
Applications
In many cases of resource allocation along with some constraint, the problem can be derived
in a similar way of Knapsack problem. Following is a set of example.
Finding the least wasteful way to cut raw materials
portfolio optimization
Cutting stock problems
tp = tp + (x[i] * profit[i]);
int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
return(0);
}
Output
Experiment:10
Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of
cities, the problem is to find the shortest possible route that visits every city exactly once and
returns back to the starting point.
Note the difference between Hamiltonian Cycle and TSP. The Hamiltoninan cycle problem is
to find if there exist a tour that visits every city exactly once. Here we know that Hamiltonian
Tour exists (because the graph is complete) and in fact many such tours exist, the problem is
to find a minimum weight Hamiltonian Cycle.
For example, consider the graph shown in figure on right side. A TSP tour in the graph is 1-2-
4-3-1. The cost of the tour is 10+25+30+15 which is 80.
The problem is a famous NP hard problem. There is no polynomial time know solution for
this problem.
Examples:
10 + 20 + 30 + 15 := 80
#include<stdio.h>
#include<conio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
scanf("%d",&n);
scanf("%d",&ary[i][j]);
completed[i]=0;
printf("\n");
printf("\t%d",ary[i][j]);
}
}
int i,ncity;
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
mincost(ncity);
int least(int c)
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
if((ary[c][i]!=0)&&(completed[i]==0))
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
if(min!=999)
cost+=kmin;
return nc;
int main()
takeInput();
getch();
return 0;
Output
Experiment:11
A Multistage graph is a directed graph in which the nodes can be divided into a set of stages
such that all edges are from a stage to next stage only (In other words there is no edge
between vertices of same stage and from a vertex of current stage to previous stage).
We are give a multistage graph, a source and a destination, we need to find shortest path from
source to destination. By convention, we consider source at stage 1 and destination as last
stage.
#include<stdio.h>
#include<conio.h>
#define max 10
int w[max][max];
int n_size;
int p[max];
void in_dat()
int i;
int j;
scanf("%d",&n_size);
for(i=0;i<n_size;i++)
w[i][i] = 0;
for(j=i+1;j<n_size;j++)
{
scanf("%d",&w[i][j]);
w[j][i] = 0;
void dis_dat()
int i;
int j;
printf("\n ");
for(i=0;i<n_size;i++)
printf("\n");
for( j=0;j<n_size;j++)
printf("\t %d",w[i][j]);
getch();
fflush(stdin);
if(sr == dst)
return 0;
else
{
int tdst;
int i;
for(i=0;i<n_size;i++)
if(w[sr][i] != 0)
ret = 0;
tdst = w[sr][i]+findshort(i,dst);
if(min >tdst)
min = tdst;
p[sr] = i;
if(ret == -1)
return INFINITY;
else
return min;
void MSG()
char s,d;
int si,di;
int dist;
scanf("%c %c",&s,&d);
fflush(stdin);
si = (int) s-65;
di = (int) d-65;
dist=findshort(si,di);
printf("\n The shortest distance between '%c' and '%c' can't be computed");
else
while(si!=di)
printf(" %c",65+p[si]);
si = p[si];
getch();
int main()
clrscr();
in_dat();
dis_dat();
MSG();
getch();
return 0;
Output