0% found this document useful (0 votes)
9 views37 pages

Daa Lab 1

The document outlines the practical lab sessions for the Design and Analysis of Algorithm course at KCC Institute of Technology & Management for the academic year 2024-25. It includes a list of algorithms to be implemented, such as Insertion Sort, Selection Sort, and Quick Sort, along with their objectives, algorithms, and sample code. Each program is designed to help students understand and apply various sorting and searching techniques in computer science.

Uploaded by

Rohit Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views37 pages

Daa Lab 1

The document outlines the practical lab sessions for the Design and Analysis of Algorithm course at KCC Institute of Technology & Management for the academic year 2024-25. It includes a list of algorithms to be implemented, such as Insertion Sort, Selection Sort, and Quick Sort, along with their objectives, algorithms, and sample code. Each program is designed to help students understand and apply various sorting and searching techniques in computer science.

Uploaded by

Rohit Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

KCC Institute of Technology & Management

Design and Analysis of Algorithm Lab (BCS -553)


Session 2024-25

Department of Computer Science and Engineering

Student Name:………………………………….

AKTU Roll no:………………………………….

Branch:…………………………………………..

Faculty In charge: Dr.Anurag Upadhyay


S.no Name of Practical Date Grade Signature
1. Implementation of Insertion
Sort
2. Implementation of Selection
Sort
3. Implementation of Shell Sort
4. Implementation of Bubble
Sort
5. Implementation of Merge
Sort
6. Implementation of Quick
Sort
7. Implementation of Linear
and Binary Search
8. Implementation of Heap Sort
9. Implementation of Gready
Fractional Knapsack.
10. Implementation of MST
using Kruskal Method.

11. Implementation of N-Queens


problem
12. Implementation of
Travelling Salesman
Program-01
Objective: Implementation of Insertion Sort
Algorithm:
Insertion Sort(A)
1. for j2tolength(A)
2. dokeyA[j]
3. |>comment insert A[j] into the second sequence
4. ij-1
5. whilei>0andA[i]>key
6. doA[i+1]A[i]
7. ii-1
8. A[i+1]key

CODE:
#include<stdio.h>
voidinsert(inta[],int n)
{
inti,j, temp;
for(i=1;i<n;i++){ temp
= a[i];
j= i-1;
while(j>=0&&temp<=a[j])
{
a[j+1]=a[j];
j = j-1;
}
a[j+1]=temp;
}
}
voidprintArr(inta[],intn)
{
inti;
for (i = 0; i < n; i++)
printf("%d",a[i]);
}
intmain()
{
inta[] = {12,31,25,8,32,17};
int n = sizeof(a) / sizeof(a[0]);
printf("Beforesortingarrayelementsare-
\n");
printArr(a,n);
insert(a, n);
printf("\nAftersortingarrayelementsare-
\n");
printArr(a,n);
return 0;
}
Output:
Program-02
Objective: Implementation of Selection Sort
Algorithm:
SelectionSort(A,n)
1. Fori=1ton-1

2.Min=i
3. Forj=j+1 ton

4. IfA[j]<A[min]
6. Min=j
7. Ifmin!=i
8. A[min]<->A[i]

CODE:
#include<stdio.h>
voidselection(intarr[],intn)
{
inti,j, small;
for(i=0;i<n-1;i++)
{
small=i;
for(j= i+1;j<n;j++) if
(arr[j] < arr[small])
small=j;
inttemp=arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}
voidprintArr(inta[],intn)
{
inti;
for (i = 0; i < n; i++)
printf("%d",a[i]);
}

intmain()
{
inta[] = {12,31,25,8,32,17};
int n = sizeof(a) / sizeof(a[0]);
printf("Beforesortingarrayelementsare-
\n");
printArr(a, n);
selection(a,n);
printf("\nAftersortingarrayelementsare-
\n");
printArr(a,n);
return 0;
}
Output:
Program-03

Objective: Implementation of Shell Sort


Algorithm:
The algorithm for shellsort can be defined in two steps--
Step 1 : Divide the original list into smaller lists
Step2:Sortindividualsublistusinganyknownsortingalgorithm.

Code:
#include<stdio.h>
voidshellSort(intarray[],intn){
for(intinterval=n/2;interval>0;interval/=2){ for (int
i = interval; i < n; i += 1) {
inttemp=array[i];
int j;
for(j=i;j>=interval&&array[j-interval]>temp;j-=interval){ array[j] =
array[j - interval];
}
array[j]=temp;
}
}
}
voidprintArray(intarray[],intsize)
{ for (int i = 0; i < size; ++i)
{ printf("%d", array[i]);
}
printf("\n");
}
intmain(){
intdata[]={9,8,3,7,5,6,4,1};
intsize=sizeof(data)/sizeof(data[0]);
shellSort(data, size);
printf("Sortedarray:\
n"); printArray(data,
size);
}

Output:
Program-04

Objective:- Implementation of Bubble Sort


Algorithm:-
begin BubbleSort(arr)
forallarrayelements
if arr[i] > arr[i+1]
swap(arr[i],arr[i+1])
end if
end for
returnarr
endBubbleSort

Code:-
#include<stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enternumberofelements\n");
scanf("%d", &n);
printf("Enter%dintegers\n",n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
for(c= 0;c < n -1;c++)
{
for(d=0;d < n- c -1;d++)
{
if(array[d] > array[d+1])
{
swap = array[d];
array[d] = array[d+1]
;
array[d+1 = swap;
]
}
}
}
printf("Sortedlistinascendingorder:\n");
for (c = 0; c < n; c++)
printf("%d\n",array[c]);
return 0;
}

Output:-
Program-05

Objective:-Implementation of Merge Sort


Algorithm:-
MERGE_SORT(arr,beg,end)

ifbeg<end
set mid = (beg + end)/2
MERGE_SORT(arr, beg, mid)
MERGE_SORT(arr, mid + 1,end)
MERGE (arr, beg, mid, end)
endofif

ENDMERGE_SORT

Code:-
#include<stdio.h>
void merge(intarr[],intp,intq,intr) { int
n1 = q - p + 1;
int n2 = r - q;
intL[n1],M[n2];
for(inti=0;i<n1;i++) L[i] =
arr[p + i];
for(intj=0;j<n2;j++) M[j] =
arr[q + 1 + j];
inti,j,k;
i =0;
j =0;
k =p;
while(i<n1&&j<n2){ if
(L[i] <= M[j]) {
arr[k]=L[i];
i++;
}
else{
arr[k]=M[j];
j++;
}
k++;
}

while(i < n1){


arr[k] = L[i];
i++;
k++;
}
while(j < n2){
arr[k] = M[j];
j++;
k++;
}
}
voidmergeSort(intarr[],intl,intr){ if
(l < r) {
intm= l+(r -l)/ 2;
mergeSort(arr l,m);
,
mergeSort(arr m+1, r);
,
merge(arr,l,m,r);
}
}
voidprintArray(intarr[],intsize)
{ for (int i = 0; i < size; i++)
printf("%d",arr[i]); printf("\
n");
}
intmain(){
intarr[]={6,5,12,10,9, 1};
intsize=sizeof(arr)/sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
printf("Sorted array: \n");
printArray(arr, size);
}

Output:-
Program-06

Objective:- Implementation of Quick Sort


Algorithm:-
Ouicksort(A,p,r)
1. ifp<r
2. thenqpartition(A,p,r)
3. quicksort(A,p,q-1)
4 quicksort(A,p+1,r)

PARTITION(A,p,r)
1. XA[r]
2. ip-1
3. Forjptor-1
4. doifA[j]<=x
5. Thenii+1
6. ExchangeA[i]A[j]
7. ExchangeA[i+1]A[r]
8. Returni+1

CODE:-
#include<stdio.h>
voidswap(int*a,int*b){ int
t = *a;
*a= *b;
*b= t;
}
intpartition(intarray[], intlow,inthigh){ int
pivot = array[high];
inti=(low- 1);
for(intj=low;j<high;j++){ if
(array[j] <= pivot) {
i++;
swap(&array[i],&array[j]);
}
}
swap(&array[i+1],&array[high]);
return (i + 1);
}
voidquickSort(intarray[],intlow,inthigh){ if
(low < high) {
intpi=partition(array,low,high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
voidprintArray(intarray[],intsize)
{ for (int i = 0; i < size; ++i) {
printf("%d",array[i]);
}
printf("\n");
}
intmain(){
intdata[]={8,7,2,1,0,9, 6};
intn=sizeof(data)/sizeof(data[0]);
printf("Unsorted Array\n");
printArray(data, n);
quickSort(data,0,n- 1);
printf("Sortedarrayinascendingorder:\n");
printArray(data, n);
}
Output:-
Program-07

Objective:- Implementation of Linear and Binary Search


Algorithm:-
LinearSearch
Linear Search(ArrayA, Valuex) 1:
Set I to 1
2: ifI> nthengotostep7
3:ifA[i]=x then gotostep6 4:
Set I to I + 1
5:GotoStep2
6: Print Elementx Found atindex I and go to step 8
7: Print element not found
8:Exit
BinarySearch
1. Def.binarySearch(A,x):
2. N=only(A)
3. Beg=0
4. End=n–1
5. Result=-1
6. While(beg<=end):
7. Mid =(beg+end)/2
8. If(A[mid]<=x):
9. Beg=mid+1
10.result=mid
11.Else:
12.end=mid–1
Return result
Code:-
Linearsearch
#include<stdio.h>
intsearch(intarray[],intn,intx){ for
(int i = 0; i < n; i++)
if(array[i]==x)
return i;
return-1;
}
intmain(){
intarray[]={2,4,0,1,9}; int
x = 1;
intn=sizeof(array)/sizeof(array[0]);
int result = search(array, n, x);
(result==-1)?printf("Elementnotfound"):
printf("Element found at index: %d", result);
}
Binarysearch
#include<stdio.h>
intbinarySearch(intarray[],intx,intlow,int
high) {
while(low<=high){
intmid=low+(high-low)/2; if
(array[mid] == x)
return mid;
if(array[mid]<x)
low=mid+1;
else
high=mid-1;
}
return-1;
}
intmain(void) {
intarray[]={3,4,5,6,7,8,9};
intn=sizeof(array)/sizeof(array[0]);
int x = 4;
intresult=binarySearch(array,x,0,n-1); if
(result == -1)
printf("Notfound");
else
printf("Elementisfoundatindex%d",result);
return 0;
}

Output:-
LinearSearch:

BinarySearch:
Program-08

Objective:- Implementation of Heap Sort


Algorithm:-
Heap sort
(A)BuildMaxHeap[
A]
1. fori<--length[A]downto2
2. doexchangeA[I]← A[i].
3. Heap.Size(A)←heapsize[A]-l
4. MaxHeapefy(A,l)
MaxHeapify(A,i)
1. l<--left[i]
2. r<--right[i]
3. ifI<=heapsize[A]andA[l]>A[I]
4. thenlargest<--I
5. elselargest<--i
6. ifr<=heapsize[A]andA[r]>A[largest]
7. thenlargest<--r
8. iflargest!=i
9. thenenchangeA[i]<-->A[largest]
10.MaxHeapify(A,Largest)

Code:-
#include<stdio.h>
voidswap(int*a,int*b){ int
temp = *a;
*a=*b;
*b=temp;
}
voidheapify(intarr[],intn,inti){
intlargest=i;
int left = 2 * i +
1; intright=2*i+2;
if(left<n&&arr[left]>arr[largest])
largest = left;
if(right<n&&arr[right]>arr[largest])
largest = right;
if (largest != i)
{ swap(&arr[i],&arr[largest
]); heapify(arr, n,
largest);
}
}
voidheapSort(intarr[],intn){
for(inti=n/2-1;i>=0;i--)
heapify(arr, n, i);
for(inti= n-1;i >=0;i--){
swap(&arr[0],&arr[i]);
heapify(arr, i, 0);
}
}
voidprintArray(intarr[],intn)
{ for (int i = 0; i < n; ++i)
printf("%d",arr[i]);
printf("\n");
}
intmain(){
intarr[]={1,12,9,5,6,10};
intn=sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
printf("Sortedarrayis\n");
printArray(arr, n);
}
Output:-
Program-09
Objective:- Implementation of Gready Fractional
Knapsack.
Algorithm:-
GreadyFractionalKnapsack()
1.{
2. Fori=1ton
3. dox[i]=0
4. Weight=0;
5. Fori1ton
6. Ifweight+w<=W
7. Thenxi=1
8. Weight=weight+w[i]
9. Elsex[i]=(w-weight)/wi
10. Weight=w
11. Break
12. Returnx
13. }

CODE:-
#include<stdio.h>
int n = 5;
intc[10]={12,1,2,1, 4};
intv[10]={4,2,2,1, 10};
intW=15;
voidsimple_fill()
{ int cur_w;
float
tot_v; int
i, maxi;
intused[10]
;
for(i=0;i<n;++i)
used[i] = 0;
cur_w=W;
while(cur_w>0){
maxi =-1;
for (i = 0; i < n; +
+i)
if((used[i]==0)&&
((maxi==-1)||((float)v[i]/c[i]
>(float)v[maxi]/c[maxi])))
maxi=i;
used[maxi] = 1;
cur_w-=c[maxi];
tot_v+=v[maxi];
if (cur_w >= 0)
printf("Added object %d (%d$,
%dKg) completelyinthebag.Spaceleft:%d.\
n",maxi+ 1, v[maxi], c[maxi], cur_w);
else{
printf("Added %d%% (%d$, %dKg) of
object %d in the bag.\n", (int)((1 +
(float)cur_w/c[maxi])*100),v[maxi],c[maxi],
maxi + 1);
tot_v-=v[maxi];
tot_v+=(1+(float)cur_w/c[maxi])*
v[maxi];
}
}
printf("Filledthebagwithobjectsworth
%.2f$.\n",tot_v);
}
intmain(intargc,char*argv[]){
simple_fill();
return0;
}
Output:-
Program-10
Objective:- Implementation of MST using Kruskal
Method.
Algorithm:-
1. A(|)
2. foreachvertexu(-V(G)
3. doMakeSet(v)
4. sorttheedgeofEintonondecreasingorderbyweightW
5. foreachedge(u,v)(-Etakeninnondecresingorder byweightW
6. doiffindset(u)=/findset(v)
7. thenAAU{(u,v)}
8. union(u,v)
9. returnA

CODE:-
#include <stdio.h>
#define MAX 30
typedefstructedge{
intu,v,w;
} edge;
typedefstructedge_list{ ed
ge data[MAX];
intn;
} edge_list;
edge_listelist;
intGraph[MAX][MAX],n;
edge_list spanlist;
void kruskalAlgo();
intfind(intbelongs[],intvertexno);
voidapplyUnion(intbelongs[],intc1,intc2);
void sort();
voidprint();
voidkruskalAlgo(){
intbelongs[MAX],i,j,cno1,cno2;
elist.n = 0;
for(i=1; i<n;i++)
for(j=0;j<i;j++)
{ if(Graph[i][j]!=0)
{
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w=Graph[i][j];
elist.n++;
}
}

sort();
for(i=0;i<n;i++)
belongs[i] = i;
spanlist.n=0;
for(i=0;i<elist.n;i++){
cno1=find(belongs,elist.data[i].u)
;
cno2=find(belongs,elist.data[i].v)
; if (cno1 != cno2) {
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}
intfind(intbelongs[],intvertexno)
{ return (belongs[vertexno]);
}
voidapplyUnion(intbelongs[],intc1,intc2){
inti;
for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}
voidsort()
{ int i, j;
edge temp;
for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1; j++)
if(elist.data[j].w>elist.data[j+1].w)
{ temp = elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j + 1] = temp;
}
}
voidprint()
{ inti,cost=0;
for (i = 0; i < spanlist.n; i++)
{ printf("\n%d-%d:
%d",spanlist.data[i].u,
spanlist.data[i].v,spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}
printf("\nSpanningtreecost:%d",cost);
}
intmain(){
inti,j,total_cost;
n = 6;
Graph[0] = 0;
[0]
Graph[0] = 4;
[1]
Graph[0] = 4;
[2]
Graph[0] = 0;
[3]
Graph[0] = 0;
[4]
Graph[0] = 0;
[5]
Graph[0] = 0;
[6]
Graph[1] = 4;
[0]
Graph[1] = 0;
[1]
Graph[1] = 2;
[2]
Graph[1] = 0;
[3]
Graph[1] = 0;
[4]
Graph[1] = 0;
[5]
Graph[1] = 0;
[6]
Graph[2] = 4;
[0]
Graph[2] = 2;
[1]
Graph[2] = 0;
[2]
Graph[2] = 3;
[3]
Graph[2] = 4;
[4]
Graph[2] = 0;
[5]
Graph[2] = 0;
[6]
Graph[3] = 0;
[0]
Graph[3] = 0;
[1]
Graph[3] = 3;
[2]
Graph[3] = 0;
[3]
Graph[3] = 3;
[4]
Graph[3] = 0;
[5]
Graph[3] = 0;
[6]
Graph[4] = 0;
[0]
Graph[4] = 0;
[1]
Graph[4] = 4;
[2]
Graph[4] = 3;
[3]
Graph[4] = 0;
[4]
Graph[4] = 0;
[5]
Graph[4] = 0;
[6]
Graph[5] = 0;
[0]
Graph[5] = 0;
[1]
Graph[5] = 2;
[2]
Graph[5] = 0;
[3]
Graph[5] = 3;
[4]
Output:-
Program-11
Objective:- Implementation of N-Queens problem.
Algorithm:-
N-Queens(k,n)
1. fori1ton
2. doif place(k,i)
3. thenn[k]i
4. if(k=n)
5. thenwrite(n,(1….n))
6. elseN-Queens(k+1,n);

PLACE(k,i)
1. for j1tok-1
2. doif(x(j)=1)or abs(x(j)-1)=(abs(j-k))
3. thenreturnfalse
4. elsereturntrue

CODE:-
#include<stdio.h>
#include<math.h>
intboard[20],count;
int main()
{
intn,i,j;
voidqueen(introw,intn);
printf("-NQueensProblemUsingBacktracking-");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
voidprint(intn)
{
inti,j;
printf("\n\nSolution%d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j)
{
if(board[i]==
j) printf("\
tQ"); else
printf("\t-");
}
}
}
intplace(introw,intcolumn)
{
inti;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-
row)) return 0;
}
return 1;
}
voidqueen(introw,intn)
{
int column; for(column=1;column<=n;
++column)
{
if(place(row,column))
{
board[row]=colum
n; if(row==n)
print(n);
else
queen(row+1,n)
;
}}}
OUTPUT:-
Program-12
Objective:- Implementation of Travelling Salesman
Problem.
Algorithm:-
C({1},1)=0
fors=2tondo
for all subsets S Є {1, 2, 3, … , n} of size s and containing 1
C (S, 1) = ∞
foralljЄSandj≠1
C(S,j)=min{C(S–{j},i)+d(i,j)foriЄSandi≠j}
ReturnminjC({1,2,3,…,n},j)+d(j,i)

CODE:-
#include<stdio.h>
intmatrix[25][25],visited_cities[10],limit,cost
= 0;
inttsp(int c)
{
intcount,nearest_city=999;
int minimum = 999, temp;
for(count=0;count<limit;count++)
{
if((matrix[c][count]!=0)&&
(visited_cities[count] == 0))
{
if(matrix[c][count]<minimum)
{
minimum=matrix[count][0]+matrix[c][count];
}
temp=matrix[c][count];
nearest_city = count;
}
}
if(minimum!=999)
{
cost=cost+temp;
}
returnnearest_city;
}
voidminimum_cost(intcity)
{
int nearest_city;
visited_cities[city]=1;
printf("%d ", city + 1);
nearest_city=tsp(city);
if(nearest_city == 999)
{
nearest_city=0;
printf("%d",nearest_city+1);
cost=cost+matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}
intmain()
{
inti,j;
printf("EnterTotalNumberofCities:\t");
scanf("%d", &limit);
printf("\nEnterCostMatrix\
n"); for(i = 0; i < limit; i+
+)
{
printf("\nEnter%dElementsinRow[%d]\n",limit,
i + 1);
for(j=0;j<limit;j++)
{
scanf("%d",&matrix[i][j]);
}
visited_cities[i]=0;
}
printf("\nEnteredCostMatrix\n");
for(i = 0; i < limit; i++)
{
printf("\n");
for(j=0;j<limit;j++)
{
printf("%d",matrix[i][j]);
}
}
printf("\n\nPath:\t");
minimum_cost(0); printf("\n\
nMinimumCost:\t");
printf("%d\n", cost);
return0;
}
OUTPUT:-

You might also like