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

Data Structure Lab Record

Linked list

Uploaded by

Desta Dan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Data Structure Lab Record

Linked list

Uploaded by

Desta Dan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Linked list

Aim:
To implement the linked lst concept with insert,delete,and reverse function.

Description: A linked list is one of the linear data structure that is used to sort the data.The
linked list is the collection of nodes each node is used to to store data. A node consists of two
points the first point stores the data and the second will contain the address of the next node.
Each node is dynamically created memory.the head is used to store the address of the the
first node. We can traverse through the linked list using only head node. The last node will be
have null in address point.

Algorithm
Create: This algorithm creates a list for a given N nodes.

Step 1: start

Step 2: Accept number of nodes into count

Step 3: repeat step 4 to step 6 until the count ! =0’

Step 4: If list empty read data to x and assign T-> data=x and t->next=null. If Head =NULL
then head=temp [first node created]

Step 5: else

5.1: repeat 5.7 until linked list T !=NULL

5.2: SET T: =link(T)

5.3: set link (T) =temp

Step 6: decrement count by 1

Step 7: stop

Display: this algorithm traverse the linked list and display data of each node.

Step 1: start

Step 2: set temp =head

Step 3 : reapeat step 5,4 and 5 until temp! =NULL

Step 4: print info(temp)

Step 5: set temp=link(temp)

Step 6: stop.
Insert: This function inserts a new node it given position

Step 1: start

Step 2: read position into pos!=0.

Step 3: create a new node and store the data and assign link(temp)=NULL

Step 4: If pos=1

4.1: set link(temp)=Head

4.2: Go to step 7

Step 5 : else if pos:= middle set p:=1

5.1: Repeat step 5.2 until p< pos and link (T)!=NULL

5.2: Increment p by 1.

5.3: set T:=Link(T) (T is the next node)

5.4: set Link(temp)=Link(T)

5.5: set Link(temp)=Link(T)

5.6: set Link(T)=temp

5.7: Increment count by 1

5.8: Go to step 7

Stop 6: Else

6.1: print No position found

Step 7: Stop

Delete: To delete a node in the linked list the algorithm is

Step 1: start

Step 2: read the position into pos

Step 3: if (pos==)

3.1 : set T: =Root

3.2 : set Root =Link(root)

3.3 : delete node T and count:=count-1

3.4 : Go to step 6
Step 4: Else

4.1 : If pos>1 and pos<=count

4.2 : set:=2 and T:=Root

4.3 : Repeat step 4.4 and until p<pos and Link(T)=NULL

4.4 : Increment p by 1

4.5: set T:=Link(T)

4.6: set temp=Link(T)

4.7: set T[Link]=temp[Link]

4.8: delete temp node count =count-1

Step 5: Else

5.1: print “invalid position”

Step 6: Stop

Reverse: To reverse the entire element in the list

Step 1: start

Step 2: The address of head node is received as argument in t

Step 3: Repeat step 4 until t->Link!=NULL

Step 4: call function reverse (t->link) recursively

Step 5: print t->data

Step 6: stop
PROGRAM FOR LINKED LIST OPERATIONS

#include<iostream.h>
#include<conio.h>
#include<dos.h>
struct Node
{
int info;
Node *link;
};
class List
{
Node *p,*tail,*q,*head;
int count ;
public:
List();
void display();
void insert();
void delet();
void Reverse();
};
List::List()
{
int n,i=1,x;
count =0;
cout<<”\n Enter No of the nodes:”;
cin>>n;
while(i<=n)
{
p=new node();
cout<<”\n Enter data”;
cin>>x;
p->info=x;
p->link=NULL;
count++;
if(i==1)
{
head=tail=p;
else
{
tail->link=p;
tail=p;
}
i++;
}
}
void List::delet()
{
int i=1,pos;
cout<<”\n Enter the position”;
cin>>pos;
p=head;
if(pos==1)
{
head=head->link;
delet(p);
}
else
{
while(i<pos)
{
q=p;
p=p->link;
i++;
}
}
if(p->link==NULL)
{
q->link=NULL;
delet(p);
}
else
{
q->link=p->link;
delet(p);
}
display();
}
void List::insert()
{
int pos,i;
p=new node();
cout<<”\n Enter data”;
cin>>p->info;
p->link=NULL;
cout<<”\n Enter the position”;
cin>>pos;
if(pos==1)
{
p->link=head;
head=p;
}
else
{
i=2;
q=head;
while(i<pos)
{
q=q->link;
i++;
}
if(q->link==NULL)
{
q->link=p;
}
else
{
p->link= q->link;
q->link=p;
}
display();
}
void List:: reverse()
{
Node *ptr=head,*temp,*pn=NULL;
cout<<endl;
while(ptr!=NULL)
{
temp=ptr->link;
ptr->link=pn;
pn=ptr;
ptr=temp;
}
head=pn;
}

void List::display()
{
cout<<endl<<”\n The List is :”;
for(p=head;p!=NULL;p= p->link)
cout<<p->info<<” ”;
}
void main()
{
List l;
int ch;
do
{
cout<<endl<<”\t\t\t The linked List”;
cout<<endl<<”\t\t\t +++++++++++”;
cout<<endl<<”\t\t\t 1.display”;
cout<<endl<<”\t\t\t 2.Insert”;
cout<<endl<<”\t\t\t 3. Delet”;
cout<<endl<<”\t\t\t 4. Reverse”;
cout<<endl<<”\t\t\t 5. Exit”;
cout<<endl<<endl<<”\t\t\t Enter Your Choice”;
cin>>ch;
switch(ch)
{
case 1:

l.Display();
break;

case 2:
l.insert();
break;
case 3: l.delet();

break;
case 4: l.Reverse();
l.display();
break;
default:
cout<<endl<<”Invalid
choice”;
} }
while(ch<5); }
OUTPUT :

Enter No of Nodes 4

Enter Data 2 4 6 8

Linked List
1. Display
2. Insert

3. Delete

4. Reverse

5. Exit

Enter your choice 2

Enter Data 10

Enter position 3

The List is 2 4 10 6 8

Linked List
1. Display

2. Insert

3. Delete

4. Reverse

5. Exit

Enter your choice 4

The List is 8 10 4 2

Linked List
1. Display

2. Insert

3. Delete

4. Reverse

5. Exit

Enter your choice 5

CIRCULAR QUEUE

AIM:

Circular array implementation of queue with menu options like insert, delete,display and
exit.

Procedure:
Circular queue are implemented sequentially using array zero to max-1 elements can be
sorted in circular queue where max size of the array used is insertion and deletion are two
primitive operations performed on a circular queue initially when c queue is empty then front
=0 and rear=0.

Insertion:

1. In two situations c queue will be checked if it is full or not.


a) When front =0 and rear=0.
b) When front = rear

If the circular queue is full, then it prints overflow message otherwise find next rear
locations by statement “rear=(rear+1)%max”.

Deletion:

1) It checks the queue for empty by the condition front==-1 and rear=-1 which is
initial condition of empty queue. If it is, it prints circular queue underflow
message.
2) It check if there is any one item in the queue by condition front=rear.
3) If there is only one element then initialize front=0 and rear=0. Otherwise
increment front by 1”front=(front+1)%max” and returns deleted item.

Circular Queue Algorithm:

Insert : This procedures an element ‘a’ in to the queue.

Step 1 : [queue already filled?] if front ==0 and rear==(s-1) or if front –rear==1 then write
overflow and return.

Step 2: else

2.1 : if front==1 set front=0 and set p [++rear] =a;


2.2 : else if rear=s-1 and front! =0 set rear=-1 and set p [++rear] =a
2.3 : else step [++rear] =0

Delete : The procedure deletes an element from a queue and assigns it to the variables.

Step 1 : [if queue already empty ] if front=0 and rear=-1 then write underflow and return.

Step 2 : else

2.1 : if front= (s-1) and rear!=(s-1) then front=0


2.2 : else front=front+1 [this deletes an element]

Step 3: return

Display : This procedure displays all the elements of the queue.


Step 1: if rear<front then

1.1. Set i=front


1.2. Repeat step
1.3. Until i<3,write p[i] and increment by 1
1.4. Again set i=o
1.5. Repeat step
1.6. Write p[i] and increment i by 1

Step 2: else

2.1. Set i=front


2.2. Repeat step until i<=rear
2.3. Write p[i] and increment i by 1

Step 3: return

/* PROGRAM FOR CIRCULAR QUEUE*/


#include<iostream.h>
#include<conio.h>
#include<dos.h>

class Cirque
{
int *p,s;
int front ,rear;
public:
Cirque()
{
front=-1;
rear=-1;
}
void create();
void display();
void insert();
void delet();
};
void Cirque:: create()
{
cout<<”Enter the size of the circular queue”;
cin>>s;
p=new int[s];
cout<<”circular queue is created :”<<s<<endl;
}
void Cirque::display()
{
int i;
cout<<”\n front->”;
if(rear<front)
{
for(i=front;i<s;i++)
cout<<p[i]<<” ”;
for(i=0;i<=rear;i++)
cout<<p[i]<<” ”;
}
else
{
for(i=front;i<=rear;i++)
cout<<p[i]<<” ”;
}
cout<<”<-rear”;
}
void Cirque::insert ()
{
int a;
cout<<”\ Enter value to push in the circular
queue:”;
cin>>a;
if(front==-1)
{
front=0;
p[++rear]=a;
}
Else if(front==0&&rear==(s-1)||(front-rear==1))
cout<<”circular queue is full:”<<endl;
else
if(rear==(s-1)&&(front!=0)
{
rear=-1;
p[++rear]=a;
}
else
p[++rear]=a;
}
void Cirque::delet()
{
if(front==0&&rear==-1)
cout<<”circular queue is underflow:”;
if(front==(s-1)&&rear!=(s-1))
front=0;
else
front=front+1;
}
void main()
{
Cirque c;
int ch;
clrscr();
cout<<” menu”<<endl;
cout<<endl<<”\t\t\t +++++++++++”;
cout<<endl<<”\t\t\t 1.CREATE”;
cout<<endl<<”\t\t\t 2.push”;
cout<<endl<<”\t\t\t 3. pop”;
cout<<endl<<”\t\t\t 4. display”;
cout<<endl<<”\t\t\t 5. Exit”<<endl;
do
{
cout<<endl<<endl<<”\t\t\t Enter Your Choice”;
cin>>ch;
switch(ch)
{
case 1:

c.create();
break;

case 2:
c.insert();
break;
case 3: l.delet();

break;
case 4: c.display();

break;
default:
cout<<endl<<”Invalid
choice”;
}
}
while(ch<5);

Output
Menu

1. Create

2. Insert

3. Delete

4. Display

5. Exit

Enter your choice:1

Enter size of the circular queue: 4

Circular queue is created with size: 4

Enter your choice:2

Enter value of push in the circular queue: 9

Enter your choice:2

Enter value of push in the circular queue: 5

Enter your choice:2

Enter value of push in the circular queue: 7

Enter your choice:2

Enter value of push in the circular queue: 3

Enter your choice:2

Enter value of push in the circular queue: 6

Circular queue is full

Enter your choice: 4

Front->9 5 7 3 <-rear

Enter your choice: 3

Enter your choice: 4

Front->9 5 7 3 <-rear

Enter your choice: 3


Enter your choice: 4

Front-> 5 7 3 2<-rear

Enter your choice: 5

INFIX-POSTFIX EVALUATION
Aim:
Array implementation of stack to evaluate a given postfix expression after accepting
values of single character operands at run time
Procedure:
Simple arithmetic expression can be notated in three ways, namely, infix, postfix, and prefix
notations.
In infix notation, the operation symbol is between two operands. Eg: A+b
In Postfix notation, the operation symbol is placed after two operands. Eg: AB+
In Prefix notation, the operation symbol is placed before two operands. E.g: +AB

ALGORITHM FOR INFIX TO POSTFIX EVALUATION


Suppose Q is an arithmetic expression written infix notation. This algorithm find the
equivalent postfix expression p.
ALGORITHM
Step 1 : push ‘c’ on to stack and add “)” end of the Q
Step 2 : scan Q from left to right and repeat Step 3 to Step
6 for each element of a until the stack is empty
Step 3 : If an operand is encountered add if top.
Step 4 : If a last parenthesis is encountered push into stack
Step 5 : If an operator op is encountered then,
5.1 : Repeatedly pop from stack and add top each operator
( on the top of the stack) which has the precedence
as or higher precedence then
5.2 : Add op to stack (end of if structure]
Step 6 : “(“ “)” encountered then
6.1 : Repeatedly pop from stack and add top each operator
until “(“ is encountered.
6.2 : Remove the left parenthesis [do not add the last
Parenthesis top]
Step 7 : Return.
Precedence: This algorithm gives the precedence value of the operator Q
Step 1: i=0
Step 2: if ch = c then i=0 and return
Step 3: if ch=+ or c= - then i=1 and return
Step 4: if ch = * or ch = / then i=2 and return
Step 5: if ch = n then i=3 and return
Step 6: return
PUSH: This procedure deletes the operator from stack and adds to top
Step1: Increment top by 1
Step 2: Store the operator into stack
Step 3: return
POP: This procedure deletes the operator from the stack and adds to the top
Step 1: return operator stored at the top of the stack
Step 2: decrement top by 1
Step 3: return
EVALUAE: This algorithm finds s the value of an arithmetic expression p return in
postfix notation
Step 1: add the right prentices ‘i’ at the end of p
Step2: scan p left to right and repeat step 3 and 4 for each element at p
until the sentence ‘)’ is encountered
Step3: if an operand is encountered put it on stack
Step4: if an operator op is encountered then
a.Remove the two top element of stack where A is the top
element and B is the next two top element
b.Evaluate B of A
c.Place the result of B back on to the stack
Step 5: value 5 equal to the top element on the stack
Step 6: Exit

Implementation of Infix to postfix evaluation


#include<iostream.h>
#incluede<conio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
class inf_post
{
char stack[20],ch;
public:
char infix[20],postfix[20],top;
void infix();
void push(char ch);
char pop();
int instackpri(char ch);
int incomingpri(char ch);
void conversion();
inf_post();
{
top=0;
};
class stackpostfix:public inf_post
{
int arr[10],x,y;
public:
void result();
void calculation();
};
void inf_post::infixe()
{
cout<<"enter and infix expression:";
cin>>infixe;
}
void inf_post::push(char ch)
{
if(top>=20)
cout<<"\n stack is full";
else
{
top++;
stack[top]=ch;
}
}
char inf_post ::pop()
{
if(top==0)
{
cout<<"\nstack is empty";
ch=' ';
}
else
{
ch=stack[top];
top--;
}
return(ch);
}
int inf_post ::instackpri(char ch)
{
int i;
awitch(ch)
{
case '^':i=4;
break;
case '*':
case '/':
i=3;
break;
case '+':
case '-':
i=2;
case '(':
i=1;
break;
}
return(i);
}
int inf_post::incomingpri(char ch)
{
int j;
switch(ch)
{
case '^':j=4;
break;
case '*':
case '/':
j=3;
break;
case '+':
case '-':
j=2;
case '(':
j=5;
break;
case ')':
j=1;
break;
}
return(j);
}
void info_post::conversion()
{
int l=strlen(infix);
int j=0;
top++;
stack[top]='(';
infix[l]=')';
for(int i=0;i<l;i++)
{
switch(infix[i])
{
case '(':
push(infix[i]);
break;
case '*':
case '/':
case '+':
case '-':
case '^'
while(instackpri(stack[top]>=incomingpri(infix[i]))
{
postfix[j]=top();
j++;
}
push(infix[i]);
break;
case ')':
while(stack[top]!='('))
{
postfix[j]=pop();
j++;
}
ch=pop();
break;
default:
postfix[j]=infix[i];
j++;
}
}
postfix[j]='\O';
}
void stackpostfix::calculation()
{
x=arr[top];
top=top-1;
y=arr[top];
}
void stackpostfix::result()
int inf_post::incomingpri(char ch)
{
int length;
length =strlen(postfix);
for(int i=0;i<lenght;i++)
{
switch(postfix[i])
{
case '*':
calcuation();
arr[top]=y*x;
break;
case '/':
calcuation();
arr[top]=pow(y,x);
break;
case '+':
calcuation();
arr[top]=y+x;
break;
case '-':
calcuation();
arr[top]=y-x;
break;
default:
cout<<”enter the value of for:”<<postfix[i]<<”=”;
top=top+1;
cin>>arr[top];
}
}
cout<<” the result is :”<<arr[top]<<endl;
}
void main()
{

char opt;
stakpostfix ip;
clrscr();
do
{
ip.infixe();
ipconversion();
cout<<”the post fix conversion
is:”<<ip.postfix<<endl;
ip.result();
cout<<”do you want to continue y/n:”;
cin>>opt;
}
while(opt=='y');
}

Output:
Enter the infix expression: a+ (b/c)*(d*e)
The postfix expression is: abc/de**+

Enter the value for a: 2


Enter the value for b: 6
Enter the value for c: 3
Enter the value for d: 1
Enter the value for e: 4
The result is: 10

Do you want to continue y/n: y?


Enter an infix expression :(( a+b) +(c-d)*e)
The post fix expression is: ab+cd-e*+

Enter the value for a: 4


Enter the value for b: 2
Enter the value for c: 8
Enter the value for d: 3
Enter the value for e: 5
The result is: 31

Do you want to continue y/n: n?

Binary search tree


Aim:

A binary tree is said to be binary search tree if each node of tree as following
property:

1. The value of node ‘n’ is greater than every value of the left sub-tree of N
2. The value of node ‘n’ is less than every value in the right sub-tree of N

Analysis:

In the binary search sub-tree there are three standard ways of traversing a binary tree
with root R.

->In preorder traversal the root node is processed first traverse the left sub-tree ‘p’ and
tracers the sub-tree of R,
->In in order traversal the left sub-tree of ‘r’ process the root traversal the left sub-tree
R,
->In postorder traversal the left sub-tree of R is process first then traverse the right
sub-tree of r and then process the rot ‘r’

Example

B C

D F
E

F G

Preorder: ABCDGHCEF

Inorder: GDHBCAECF

Postorder: GHDBEFCA

Algorithm
Create( ): this algorithm is used to construct a binary search tree ‘r’ in a pointer to the
node and temp this pointer variable

Step1: Assign temp != NULL

Step2: Repeat step 3 and step 4 while (1)

Step3: Repeat an element o to terminate

Step4: If element=0 then exit

Step5: Call add()

Step6: return

Add(r, n): This algorithm is use k to add the element in the current location of binary tree r, n
are received variables at tem and ele from the function

Step1: if *r = NULL then

Create a node and assign the address k to x

Assign N value to int of ‘r’

Step 2: If info[r]>n then call address (left[r], n)

Step 3: if info [r] > n then call add

Step 4: return

Implementation of Binary search tree

#include<iostream.h>
#include<conio.h>
#include<process.h>

struct node
{
int no;
node *left;
node *right;
};
class bst
{
public:
node *root;
bst()
{
root= new node;
}
void create();
void add(node**,int);
void disp(node*,int);
void display();
};
void bst::create()
{
int ele;
node **temp=&root;
*temp=NULL;
while(1)
{
cout<<"\n enter a no at last enter 0:";
cin>>ele;
if(ele==0) break;
add(temp,ele);
}
}
void bst::add(node **r,int n)
{
if(*r==NULL)
{
*r=new node;
(*r)->no=n;
(*r)->left=NULL;
(*r)->right=NULL;
}
if((*r)->no>n)
{
clrscr();
cout<<"\n left side of the tree";
add(&(*r)->left,n);
}
if((*r)->no<n)
{
clrscr();
cout<<"\n right side of the tree";
add(&(*r)->right,n);
} }
void bst::display()
{
int ch;
while(1)
{
cout<<"\n\n\n";
cout<<"\n1.preorder"<<"\n2inorder"<<"\
n3postorder"<<"\n4exit";
cout<<"enter your choice";
cin>>ch;
if(ch==4)
break;
disp(root,ch);
}
clrscr();
}
void bst::disp(node *t,int n)
{
if(t!=NULL)
switch(n)
{
case 1:
cout<<t->no<<"->";
disp(t->left,n);
disp(t->right,n);
break;

case 2:
disp(t->left,n);
cout<<t->no<<"->";
disp(t->right,n);
break;
case 3:
disp(t->left,n);
disp(t->right,n);
cout<<t->no<<"->";
break;

default:
cout<<"\n invalid choice";
}
}
void main()
{
clrscr();
bst b1;
b1.create();
b1.display();
}

Output
Enter a number at last enter 0:100

Enter a number at last enter 0:86

Left side of the tree

Enter a number at last enter 0:105

Right side of the tree

Enter a number at last enter 0:119

Right side of the tree

Right side of the tree

Enter a number at last enter 0:84

Left side of the tree

Left side of the tree

Enter a number at last enter 0:98

Left side of the tree


Right side of the tree

Enter a number at last enter 0:32

Left side of the tree

Left side of the tree

Left side of the tree

Enter a number at last enter 0:118

Right side of the tree

Right side of the tree

Left side of the tree

MERGE SORT

Aim:

To sort the given array a of ‘n’ elements a[1],a[2],a[3],………a[n], which is in


memory so that the elements can be arranged in an order.

Description:

We use divide and conquer method to sort a file in the n sub files of size and merge
adjacent pair of files we then have approximately n/2 files sizes. Repeat this process until
there is only one file of remaining size the worst case and average are complexity of merge
sort is nlogn.

Algorithm:

Step 1: Start

Step 2: repeat 3 to 13 until siz<n

Step 3: initialize l1=k=0

Step 4: repeat 5 to 10 until l1=siz<n

Step 5: initialize step l2=l1=siz and u1=l2-1

Step 6: if l2+siz-1<n then initialize

U2 =l2+siz-1

U2= n-1

Step 7: initialize i=l1 else and j2=l2 and repeat 7.1 and until 7.2 until i<u1 and j<=u2

7.1: if arr[i]<=arr[j] then assign aux[k++]=arr[i++]

/* PROGRAM FOR MERGE SORT*/

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
class merge
{
int *a,n,temp,I;
public:
merge();
void read();
void sort();
void print();
};
merge:: merge()
{
cout<<”enter size\t”;
cin>>n;
a=new int[n];
}
void merge::read()
{
cout<<”enter elements into array\n”;
for(int i=0;i<n;i++)
{
cout<<”enter”<<1+i<<”no”;
cin>>a[i];
}
void merge::print()
{
static int y=0;
cout<<”\n\n in pass”<<++y<<”the array is”;
for(int z=0;z<n;z++)
cout<<a[z]<<”\t”;
}
void merge:: sort()
{
int j,k,i,l1,l2,siz,u1,u2;
int aux[50];
siz=1;
while(siz<n)
{
l1=k=0;
while(l1+siz<n)
{
l2=l1+siz;
u1=l2-1;
u2=(l2+siz-1<n)? l2+siz-1:n-1;
for(i=l1,j=l2;i<u1&&j<=u2;k++)
{
if(a[i]<a[j])
aux[k]=a[i++];
else
aux[k]=a[j++];
}
for(;i<=u1;k++)
aux[k]=a[i++];
for(;j<=u2;k++)
aux[k]=a[j++];
l1 =u2+1;
}
for(i=l1;k<n;i++)
aux[k++]=a[i];
for(i=0;i<n;i++)
a[i]=aux[i];
siz*=2;
print();
}
}
void main()
{
clrscr();
merge b;
b.read();
b.sort();
cout<<”\n\n Finally the sorted array is”;
b.print();
getch();
}

OUTPUT

Enter size: 5

Enter elements into array 55 77 33 99 44

In pass 1 the array is 55 77 33 99 44

In pass 2 the array is 33 55 77 99 44

In pass 3 the array is 33 44 55 77 99

Finally the sorted array is 33 44 55 77 99


QUICK SORT

Aim:

To implement the quick sort algorithm for the given elements in array to re arrange
the elements is array so they are in ascending order.

Description:

Quick sort is a fast sorting algorithm, which is used not only for educational purposes,
but widely applied in practice. On the average, it has O(n log n) complexity, making quick
sort suitable for sorting big data volumes. The Idea of the algorithm is quite as fast as bubble
sort.

We use the divide and conquer approach to perform quick sort. In this method the ‘n’
elements to be sorted are partitioned into 3 segments they are left segment middle segment
and right segment. The middle segment contains only one element. No element in left has a
key layer then the key of the element in middle and no element in the right has a key that is
smaller than the middle element so that the elements in left and middle can be sorted
independently. No merge is following the sorting of the element. the element in middle called
as pivot or partitioning element. The worst complexity of is n2 and average complexity is n
log n.

Theory:

The divided and conquer strategy is used in quick sort. Below the recursion step is described:

1. Choose a pivot value. We take the value of the middle element as pivot value, but it
can be any value, which is in range of sorted values, even if it does not present in the
array.
2. Partition. Rearrange elements in such a way, that all elements which are lesser than
the pivot go to the left part of the array and all elements greater than the pivot, go to
the right part of the array. Values equal to the pivot can stay in any part of the array.
Notice, that array may be divided in non-equal parts.
3. Sort both parts. Apply quick sort algorithm recursively to the left and the right parts.

Algorithm:

Step 1: Call the function as sort (arr,0,n-1) where arr is array, 0 is beginning, and n-1 is size
of given array.

Step2: exit

Algorithm for sort() function: sort( arr, left, right)

Step 1: if left> right then exit


Step 2: initialize I and j and asign i=left and j=right +1

Step 3: initialize pivot and assign pivot=arr[left]

Step 4: loop until true repeat steps 5 to 8

Step 5: repeat step 5.1 until arr[i] < pivot do

5.1 : i=i+1

Step 6: repeat step 6.1 until arr[j]>pivot do

6.1: j=j-1

Step 7: if i>= j break then loop of step 4 else go to step 8.

Step 8: interchange elements in arr[i] and arr[j]

Step 9: assign arr[left]=arr[j] and arr[j]= pivot

Step 10: call the function sort(arr,left, j-1) as arguments recursively.

Partition algorithm in detail

There are two indices I and j and at the very beginning of the partition algorithm I
points to the first element in the array and j points to the last one. Then algorithm moves I
forward, until an element with value greater or equal to the pivot found. Index j is moved
backward, until an element with value lesser or equal to the pivot is found. If i<= j then they
are swapped and I steps to the next position (i+1), j steps to the previous one (j-1). Algorithm
stops, when I become greater than j.

After partition, all values before ith element are less or equal than the pivot and all
values after j-th element are greater or equal to the pivot.

Example. Sort {1,12,5,26,7,14,3,7,2} using quick sort.


1 12 5 26 7 14 3 7 2 Unsorted

1 12 5 26 7 14 3 7 2
Pivot
value=7

Pivot value

12>=7>=2,swap 12 and 2

1 2 5 26 7 14 3 7 12
26>=7>=7,swap 26 and 7

1 2 5 7 7 14 3 26 12

7>=7>=3,swap 7 and 3

/* PROGRAM FOR QUICK SORT*/


#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class qsort
{
int *a,I,n,temp;
public:
qsort();
void quicksort();
void read();
void sort( int [], int, int);
void print();
};
qsort:: qsort()
{
cout<<”enter size:”;
cin>>n;
a=new int [n];
}
void qsort:: read()
{
cout<<”enter elements into array:”;
for(int i=0;i<n;i++)
cin>>a[i];
}
void qsort:: print()
{
cout<<”the elements in array are:”;
for( int z=0;z<n;z++)
cou<<a[z]<<” “;
}
void qsort::quicksort()
{
sort(a,0,n-1);
}
void qsort:: sort(int a[], int l, int r)
{
if(l>=r)return;
int i=l,j=r+1;
static int y=0;
int pivot=a[l];
int temp;
while (1)
{
do{
i=i+1;
}
while (a[i]<pivot);
do{
j=j-1;
}
while(a[j]>pivot);
if(i>j) break;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
cout<<endl<<”in pass”<<++y<<”the pivot is “<<pivot
<<”and array is:”;
print();
a[l]= a[j];
a[j]=pivot;
sort(a,l,j-1);
sort(a,j+1,r);
}
void main()
{
clrscr();
qsort b;
b.read();
b.quicksort();
cout<<endl<<”Finally the sorted array is:”;
b.print();
getch();
}

OUTPUT:
Enter size 7

Enter elements into array 99 33 55 11 55 66 77

Pass 1 the pivot is 99 and array is 99 33 55 11 55 66 77

Pass 2 the pivot is 77 and array is 77 33 55 11 55 66 99

Pass 3 the pivot is 66 and array is 66 33 55 11 55 77 99

Pass 4 the pivot is 55 and array is 55 33 11 55 66 77 99

Pass 5 the pivot is 11 and array is 11 33 55 55 66 77 99

Finally the sorted array is 11 33 55 55 66 77 99


HEAP SORT

AIM:

To write a c++ program for heap sort.

Procedure:

Heap sort is a sorting algorithm which was originally described by floyd the method
sorting by building a head and then repeatedly extracting the maximum item.

Heap is a complete binary tree with the property that a parent is always greater than or
equal to either of its children (if they exist) thus the root node always contains the largest
element.

The heap sort method takes the input array of elements to be sorted and then builds a
heap based on elements finally produces consist of two phases

1. Building a heap tree


2. Sorting
Building a heap tree:
a) Start with just one element one element always satisfies heap property
b) Insert next elements and make his heap
c) Repeat step b until all elements are included in the heap

Sorting:

a) Exchange the root and last element in heap


b) Make this heap again but this time do not include the last node
c) Repeat step a and b until there is no element left

Algorithm:

Create_heap (int I, int n): this algorithm creates heap construction


Step 1: set f=0
Step 2: set r=t[i] and j=1*2
Step 3: repeat step 4 and 8 while i<=n and f=0
Step 4: if j<n then
Step 5: if ([j+1]>t[j]) then i) j++
Step 6: if r>=t[j] then i)f=1
Step 7: else

i) T [j/2] =t[j];

j) j=2*j
step 8: t[j/2]=r
step 9: return
heap ():
step 1: set i=n/2
step 2: repeat step 3 until i>=1
step 3: arrange (I,n) and i—
step 4: set i=n-1
step 5: repeat step 6 to 10 until i>= 1
step 6: set a=t[i+1]
step 7: set t[i]=a
step 8: arrange (1,i)
step 9: i=i-1
step 10: return

PROGRAM FOR THE HEAP SORT


#include<iostream.h>
#include<conio.h>
class hsort
{
int t[20],I,n;
public:
hsort();
void arrang(int , int);
void heap();
void display();
};
hsort::hsort()
{
cout<<”\n Enter number of elements”<<endl;
cin>>n;
cout<<”enter sorting elements:”<<endl;
for(i=1;i<=n;i++)
cin>>t[i];
}
void hsort::arrang(int I, int n)
{
int j,r,f=0;
r=t[i];
j=i*2;
while((j<=n)&&(f==0))
{
if(j<n)
if(t[j+1]>t[j])
j++;
if(r>=t[j])
f=1;
else
{ t[j/2]=t[j];
j=2*j;
}
t[j/2]=r;
}
}
void hsort::heap()
{
int a;
cout<<”\n \n hai”;
for(i=n/2; i>=1;i--)
arrange(I,n);
for(i=(n-1);i>=1;i--)
{
a=t[i+1];
t[i+1]=t[1];
t[1]= a;
arrang(1,i);
}
}
void hsort::display()
{
cout<<”the sorted elements :” <<endl;
for(i=1;i<=n;i++)
cout<<”\t”<<t[i];
}
void main()
{
clrscr();
hsort h;
h.heap();
h.display();
getch();
}

OUT PUT:
Enter number of elements 6

Enter sorting elements

3 8 9 5 2 4

The sorted elements:

234589

DIJKSTRA’S ALGORITHM

AIM:
To implement Dijkstra’s algorithm to find the shortest path between any two vertices in a
weighted graph.

Definition:

Let us consider the general problem of finding the length of a shortest path between a
and z. In an undirected connected simple weighted graph. Dijkastra’s algorithm produces by
the finding length of shortest path from a to z is found.

The shortest path is defined as path from a to z such that the sum of weights of arcs on
the paths is minimized. To represent the network. We assume weight of arc from i to j. If
there is no arc from i to j, weight (I,J) is a set to an arbitrarily large value to indicate. The
infinite cost of going directly from I to J.

Algorithm

Step 1 : Assign a temporary label vi =to all vertices except vs

Step 2 : [mark vs as permanent by assigning a label to it]

L(vs)=0

Step 3 : [Assign value of vs to vr where vr is last vertex to be

made permanent vs = vr

Step 4 : if L(vi )>L(vk)+w(vk,vi )

L(vi )>L(vk)+w(vk,vi )

Step 5 : vk=vi

Step 6 : If vt is temporary label repeat step4 to

Step 7 : Otherwise the value of vt is permanent label and is equal

to shoretest paths vs to vt.

Step 8 : Exit.
PROGRAM FOR DIJKSTRA’S ALGORTHIM

#include<iostream.h>
#include<conio.h>
#define size 20
#define p 1
#define T 0
#define INFINITY 9999

struct Label
{
int predecessor, length,flag;
};
class dijkstra
{
int k,min,count,vist_path[size],n;
Label state[size];
public:
int short_path(int a[size]
[size],int,int,int,int,path[size],int*);
void input(int,int a[size][size]);
void output(int, int a[size][size]);
};
int dijkstra::short_path(int a[size][size],int
n,int s,int t,int
path[size],int *dist)
{
*dist=0;
for(int i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].length=INFINITY;
state[i].flag=T;
}
//make source vertex permanent
state[s].predecessor=0;
state[s].length =0;
state[s].flag=p;
//state from source vertex
k=s;
do
{
//check all the paths from kth vertex and find
their distance from k vertex
For(i=1;i<=n;i++)
{
if(a[k][i]>0 &&(state[i].flag==T)
if((state[k].length+a[k][i])
<state[i].length)
{
state[i].predecessor=k;
state[i].length=state[k].length+a[k]
[i];
}
}
min=INFINITY;
k=0;
for(i=1;i<=n;i++)
{
if((state[i].flag==T)&&(state[i].length<m
in)
{
Min=state[i].length;
K=i;
}
if(k==0)
Return (0);
State[k].flag=p;
}while(k!=t);

k=t;
count=1;
do
{
vist_path[count]=k;
count++;
k=state[k].predecessor;
}
while(k!=0);
//reverse the vertices since algorithm stores
path in reverse
direction
count--;
for(i=1;i<i<=count;i++)
{
t1=path[i];
t2=path[i+1];
*dist+=a[t1][t2];
}
return(count);
//input function
void dijkstra::input(int n,int a[size][size])
{
cout<<”n\input adjancey matrix\n”;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cin>>a[i][j];
cout<<”\n”;
}
}
//output function
void dijkstra::output(int n,int a[size][size])
{
cout<<”\n Adjacency matrix:\n”;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cout<<” “<<a[i][j];
cout<<”\n”;
}
}
//main Function
void main()
{
clrscr();
dijkstra dij;
int a[size][size],path[size],org,dest,dist,count,n;
cout<<”\n Input the number of vertices in the graph
:”;
cin>>n;
dij.input(n,a);
dij.output(n,a);
cout<<”\n input starting vertex :”;
cin>>org;
cout<<”input destination “;
cin>>dest;
cout<<dij.short_path(a,n,org,path,&dist);
cout<<”\n\n No of paths:”<<count;
if(dist)
{
cout<<”\n shortest path:”<<path[1];
for(int i=2;i<=count;i++)
cout<<”->”<<path[i];
cout<<”\n minimum distance :”<<dist;
}
else
cout<<”\n path does not exit \n”;
getch();
}

Output

Input the number of vertices in the Graph: 5

Input adjacency matrix

0 2 0 5 7

0 0 0 3 0

8 5 0 2 0

0 0 0 0 1

0 0 9 0 0

Adjacency Matrix

0 2 0 6 7

0 0 0 3 0

8 5 0 2 0

0 0 0 0 1
0 0 9 0 0

Input starting vertex : 1

Input destination : 5

No of paths : 4

Shortest path : 1==>2==>4==>5

Minimum distance : 6
Kruskal’s Algorithm

Aim:

Kruskal algorithm for computing the minimum spanning tree is directly based on generic
MST algorithm .it builds the MST in forest .initially ,each vertices is in its own tree in forest .
then algorithm considered each edge in turn ,ordered by increasing weight .if an edge (U,V)
connects two different tree,then (U,V) is added to the set of edges of MST and two trees
connected by an edge (U,V) are merged into a single tree on the other hand ,if and edge
(U,V) connects two vertices in the same tree ,then edge(U,V) is discarded.

Disjoint set Data structure

 Make _set(V)
Create a new set whose only member is pointed to by V.
Note that for this operation V must already be in a set
 FIND set
Return a pointer to the set containing V
 UNION(U,V)
Unites the dynamic set that contain U and V into a new set that is union of these two
sets
Algorithm
MST_KRUSKAL(G,W)

Step 1 : S<-{ } // s ultimate contains the edge of the MST

Step 2:for each vertices V in V[G]

Step 3: do make set (V)

Step 4:sort edge of E by union decreasing weights w

Step 5: for each edge (U,V) in E

Step 6: do if FIND_SET(U)≠FIND_SET(V)

Step 7: then S=S U {(U,V)}

Step 8: Union (U,V)

Step 9: Return

Program implementation of kruskal’s Algorithm


#include<iostream.h>
#include<conio.h>
class kruskal
{
private:
int n;
int graph[10][10];
int tree[10][10];
int noe;
int edges[100][4];
int sets[100][10];
int top[100];
public:
void read_graph();
void intialize();
void sort_edges();
void algorithm();
int find_node(int);
void print_min_span_t();
};
void kruskal::read_graph()
{
cout<<"Enter the number of node int the graph\n";
cin>>n;
cout<<"enter the adjacency matrix of the graph\n";
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>graph[i][j];
}
void kruskal::sort_edges()
{
int i,j;
/* intialize the edge*/

noe=0;
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
if(graph[i][j]!=0)
{
noe++;
edges[noe][1]=i;
edges[noe][2]=j;
edges[noe][3]=graph[i][j];
}
}
}
/*************************** sort edge*********/
for(i=1;i<=noe;i++)
{
for(j=i;j<=noe-1;j++)
{
if(edges[j][3]>edges[j+1][3])
{
int t=edges[j][1];
edges[j][1]=edges[j+1][1];
edges[j+1][1]=t;

t=edges[j][2];
edges[j][2]=edges[j+1][2];
edges[j+1][2]=t;

t=edges[j][3];
edges[j][3]=edges[j+1][3];
edges[j+1][3]=t;
}
}
}
/******************** print edge**********/
cout<<endl;
for(i=1;i<=noe;i++)
cout<<edges[i][1]<<edges[i][2]<<edges[i][3]<<endl;
}
void kruskal::intialize()
{
for(int i=1;i<=n;i++)
for(int j= 1;j<=n;j++)
tree[i][j]=0;
}
void kruskal::algorithm()
{
// make sor set each node
for(int i=1;i<=n;i++)
{
sets[i][1]=i;
top[i]=1;
}
for(i=1;i<=noe;i++)
{
int p1=find_node(edges[i][1]);
int p2=find_node(edges[i][2]);
cout<<p1<<"\t"<<p2<<endl;
if(p1!=p2)
{
tree[edges[i][1]][edges[i][2]]=edges[i][3];
tree[edges[i][2]][edges[i][1]]=edges[i][3];
// mix the two set
for(int j=1;j<=top[p2];j++)
{
top[p1]++;
sets[p1][top[p1]]=sets[p2][j];
}
top[p2]=0;
}
}
}
int kruskal::find_node(int n)
{
for(int i=1;i<=noe;i++)
{
for(int j=1;j<=top[i];j++)
{
if(n==sets[i][j])
return i;
}
}
return -1;
}
void kruskal :: print_min_span_t()
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<tree[i][j];
cout<<endl;
}
}
}
void main()
{
kruskal obj;
obj.read_graph();
obj.sort_edges();
obj.intialize();
obj.print_min_span_t();
}

Output
Enter the no.of nodes in the graph 3

Enter the adjacency matrix of the graph

1 2 3

4 5 6

7 8 9

Print the edges

111

122

133

225

236

339

Print Each node

1 1

1 2

1 3

1 1

1 1
1 1

Print MST

0 2 3

2 0 0

3 0 0

Simple Hashing

Aim:

Implementing a simple hash table concept using C++.

Analysis:

A hash table or hash map is data structure that uses a hash function to map identifying
values, known as keys (e.g. A person’s name), to their associated values (e.g, their telephone
number). The hash function is used to transform the key into the index (the hash) of an array
element (the slot or bucket) where the corresponding value is to be sought.

A hash function is a function h(k) which transforms a key k into an address. Hashing is
like indexing in that it involves associating a key with a relative record address. Hashing
however, is different from indexing in two important ways:

 With hashing, there is no obvious connection between the key and the location
 With hashing two different keys may be transformed to the same address
Algorithm for simple hashing:

Step 1: Represent the key in numerical form

Step 2: Fold and Add

Step 3: Divide by a prime number (say 19937) and use the remainder as the address.

Step 4: Stop
IMPEMENTATION HASH TABLE

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<string.h>

class std
{
public:
char name[10];
int num;
void get()
{
cout<<”Enter no and name”;
cin>.num>>name;
}
};
int key(char x[12])
{
int sum=0;
for(int i=0;x[i]!=’\0’;i++)
{
sum=sum+(x[i]*100+x[i++]);
sum=sum%19937;
}
return (sum%100);
}
void main()
{
int n;
clrscr();
std s;
cout<<”Enter no of records”;
cin>>n;
cfstream f(“a.txt”);
for(int i=0;i<n;i++)
{
s.get();
f.write((char *)&s,sizeof(s));
}
f.close();

cout<<”The home address are”;


ifstream ff(“a.txt);
while(ff.read((char *)&s,sizeof(s));
cout<<”The address of
“<<s.name<<”is”<<key(s.name);
ff.close();
getch();
}

OUTPUT:
Enter no of records: 3
Enter no and name 14
Rama
Enter no and name15
Krishna
Enter no and name13
Hari

The home addresses are

The address of Rama is 97

The address of Krishna is 98

The address of Hari is 38

You might also like