Sei sulla pagina 1di 37

SUBMITTED BY : VIKRANT SINGH SUBNMITTED TO : MISS.

DIVYA SHARMA

ROLL-NO : SG-16846
EXP 1:- INTRODUCTION

DAA – Introduction

An algorithm is a set of steps of operations to solve a problem performing calculation, data


processing, and automated reasoning tasks. An algorithm is an efficient method that can be
expressed within finite amount of time and space.

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.

Problem Development Steps

The following steps are involved in solving computational problems.

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

The main characteristics of algorithms are as follows −

1. Algorithms must have a unique name

2. Algorithms should have explicitly defined set of inputs and outputs

3. Algorithms are well-ordered with unambiguous operations

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:

Program to implement linked list:

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *next;
};

// This function prints contents of linked list starting from


// the given node
void printList(struct Node *n)
{
while (n != NULL)
{
printf(" %d ", n->data);
n = n->next;
}
}

int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;

// allocate 3 nodes in the heap


head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));

head->data = 1; //assign data in first node


head->next = second; // Link first node with second

second->data = 2; //assign data to second node


second->next = third;

third->data = 3; //assign data to third node


third->next = 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.

A stack is a recursive data structure. Here is a structural definition of a Stack:

a stack is either empty or


it consistes of a top and the rest which is a stack;

Program to implement stack:


#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

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

Program to implement queue:


#include <iostream.h>

#include<conio.h>

int queue[100], n = 100, front = - 1, rear = - 1;

void Insert() {

int val;

if (rear == n - 1)

cout<<"Queue Overflow"<<endl;

else {

if (front == - 1)

front = 0;

cout<<"Insert the element in queue : "<<endl;

cin>>val;

rear++;

queue[rear] = val;

}
}

void Delete() {

if (front == - 1 || front > rear) {

cout<<"Queue Underflow ";

return ;

} else {

cout<<"Element deleted from queue is : "<< queue[front] <<endl;

front++;;

void Display() {

if (front == - 1)

cout<<"Queue is empty"<<endl;

else {

cout<<"Queue elements are : ";

for (int i = front; i <= rear; i++)

cout<<queue[i]<<" ";

cout<<endl;

int main() {

int ch;

cout<<"1) Insert element to queue"<<endl;

cout<<"2) Delete element from queue"<<endl;

cout<<"3) Display all the elements of queue"<<endl;

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;

default: cout<<"Invalid choice"<<endl;

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

Program to implement quicksort:


#include<stdio.h>
#include<conio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);

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

2. Call mergeSort for first half:

Call mergeSort(arr, l, m)

3. Call mergeSort for second half:

Call mergeSort(arr, m+1, r)

4. Merge the two halves sorted in step 2 and 3:

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

Program to implement Linear Search:

#include<stdio.h>
#include<conio.h>
int main()
{
int a[20],i,x,n;
clrscr();
printf("How many elements?");
scanf("%d",&n);

printf("Enter %d array elements:\n",n);


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter element to search:");
scanf("%d",&x);

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.

Program to implement binary search:

#include <stdio.h>
#include<conio.h>

int 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);

return 0;

Output
Experiment:9

Knapsack Problem using greedy method:

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

Program to implement knapsack problem using greedy method


# include<stdio.h>

void knapsack(int n, float weight[], float profit[], float capacity) {


float x[20], tp = 0;
int i, j, u;
u = capacity;

for (i = 0; i < n; i++)


x[i] = 0.0;

for (i = 0; i < n; i++) {


if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];

tp = tp + (x[i] * profit[i]);

printf("\nThe result vector is:- ");


for (i = 0; i < n; i++)
printf("%f\t", x[i]);

printf("\nMaximum profit is:- %f", tp);

int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;

printf("\nEnter the no. of objects:- ");


scanf("%d", &num);

printf("\nEnter the wts and profits of each object:- ");


for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}

printf("\nEnter the capacityacity of knapsack:- ");


scanf("%f", &capacity);

for (i = 0; i < num; i++) {


ratio[i] = profit[i] / weight[i];
}

for (i = 0; i < num; i++) {


for (j = i + 1; j < num; j++) {
if (ratio[i] < ratio[j]) {
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = 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

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:

Output of Given Graph:

minimum weight Hamiltonian Cycle :

10 + 20 + 30 + 15 := 80

Program on Travelling Salesman Problem:

#include<stdio.h>

#include<conio.h>

int ary[10][10],completed[10],n,cost=0;

void takeInput()
{

int i,j;

printf("Enter the number of villages: ");

scanf("%d",&n);

printf("\nEnter the Cost Matrix\n");

for(i=0;i < n;i++)

printf("\nEnter Elements of Row: %d\n",i+1);

for( j=0;j < n;j++)

scanf("%d",&ary[i][j]);

completed[i]=0;

printf("\n\nThe cost list is:");

for( i=0;i < n;i++)

printf("\n");

for(j=0;j < n;j++)

printf("\t%d",ary[i][j]);

}
}

void mincost(int city)

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))

if(ary[c][i]+ary[i][c] < min)

min=ary[i][0]+ary[c][i];

kmin=ary[c][i];

nc=i;

if(min!=999)

cost+=kmin;

return nc;

int main()

takeInput();

printf("\n\nThe Path is:\n");

mincost(0); //passing 0 because starting vertex

printf("\n\nMinimum cost is %d\n ",cost);

getch();
return 0;

Output
Experiment:11

Multistage Graph (Shortest Path)

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.

Program on Multistage Graph:

#include<stdio.h>

#include<conio.h>

#define max 10

#define INFINITY 1000

int w[max][max];

int n_size;

int p[max];

void in_dat()

int i;

int j;

printf("\n\t Multi-Stage Graph \n");

printf("\n Enter the number of nodes : ");

scanf("%d",&n_size);

for(i=0;i<n_size;i++)

w[i][i] = 0;

for(j=i+1;j<n_size;j++)
{

printf("Enter the weight of edge '%c' to '%c': ",65+i,65+j);

scanf("%d",&w[i][j]);

w[j][i] = 0;

void dis_dat()

int i;

int j;

printf("\n The Path adjacent matrix \n");

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

int findshort(int sr,int dst)

if(sr == dst)

return 0;

else
{

int ret = -1;

int min = INFINITY;

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;

printf("\nEnter the source and destination node : ");

scanf("%c %c",&s,&d);

fflush(stdin);

si = (int) s-65;

di = (int) d-65;

dist=findshort(si,di);

if(dist >= INFINITY)

printf("\n The shortest distance between '%c' and '%c' can't be computed");

else

printf("\n The shortest distance between '%c' and '%c' : %d",s,d,dist);

printf("\n The shortest path : %c",s);

while(si!=di)

printf(" %c",65+p[si]);

si = p[si];

getch();

int main()

clrscr();

in_dat();

dis_dat();
MSG();

getch();

return 0;

Output

Potrebbero piacerti anche