1. 1
LAB 1
INTRODUCTION TO CLASS
OBJECTIVES:
To be able to debug and run C++ programs
Write C++ programs to create functions and passing arguments.
Implementation of basic concepts of object oriented programming in C++ such as
Class creation, defining data members and data functions.
To learn how to access Class members, and create constructors and destructors.
INTRODUCTION:
A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package. The data and functions within a
class are called members of the class. A class provides the blueprints for objects, so basically
an object is created from a class. We declare objects of a class with exactly the same sort of
declaration that we declare variables of basic types.
In class-based object-oriented programming, A class constructor is a special member
function of a class that is executed whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at
all, not even void. Constructors can be very useful for setting initial values for certain
member variables
A destructor is a special member function of a class that is executed whenever an object of
its class goes out of scope or whenever the delete expression is applied to a pointer to the
object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can
neither return a value nor can it take any parameters. Destructor can be very useful for
releasing resources before coming out of the program like closing files, releasing memories
etc.
ACCESS SPECIFIERS:
Public - The members declared as Public are accessible from outside the Class through an
object of the class.
Protected - The members declared as Protected are accessible from outside the class but only
in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is
allowed.
CLASS MEMBER FUNCTIONS:
2. 2
A member function of a class is a function that has its definition or its prototype within the
class definition like any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
PROGRAM 1
Write a program to enter marks of 6 different subjects and find out the total mark (Using can
and cout statement).
Algorithm:
1: Declare variables.
2: Take marks of six subjects
3: Add the marks and store in a variable
4: Display marks.
PROGRAM 2
Write a function using reference variables as arguments to swap the values of pair of integers.
Algorithm:
1: Declare variables.
2: Define a function Swap that take two values as arguments.
3: Take input from user
4: call swap function, by sending variables containing input to swap function.
5: Display swapped variables.
Pseudo code for Swap function:
swap(x,y)
begin
set z=x
set x=y
set y=z
end
POST LAB:
Create a Class named Box
1: take input for length, width and height.
2: Declare three member functions to take input values, calculate volume of box and
displaying result. 3: Also define constructor and destructor.
3. 3
LAB 2
ONE AND TWO DIMENSIONAL ARRAYS
OBJECTIVE:
One and Two Dimensional Arrays of primitives as well as references types are defined and
operations like copying, cloning, insertion and deletion are performed on them.
INTRODUCTION TO ARRAYS:
An array is a series of elements of the same type placed in contiguous memory locations that
can be individually referenced by adding an index to a unique identifier.
For example, an array containing 5 integer values of type int called foo could be represented
as
Like a regular variable, an array must be declared before it is used. A typical declaration for
an array in C++ is:
type name [elements];
Initializing Array
By default, regular arrays of local scope (for example, those declared within a function) are
left uninitialized. This means that none of its elements are set to any particular value; their
contents are undetermined at the point the array is declared.
But the elements in an array can be explicitly initialized to specific values when it is declared,
by enclosing those initial values in braces {}. For example:
int arr [5] = { 16, 2, 77, 40, 12071 };
Accessing value of an array
The values of any of the elements in an array can be accessed just like the value of a regular
variable of the same type. The syntax is:
name [index]
4. 4
MULTIDIMENSIONAL ARRAYS:
Multidimensional arrays can be described as "arrays of arrays". For example, a bi-
dimensional array can be imagined as a two-dimensional table made of elements, all of them
of a same uniform data type
Two dimensional arrays:
int x [3] [4];
Here, x is a two dimensional array. It can hold a maximum of 12 elements.
PRE LAB TASK:
C++ Program to display marks of 5 students by passing one-dimensional array to a function
Procedure:
1: Take input through enters function.
2: Call display function to display the marks of students by passing an array as arguments.
3: call both functions from main.
C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.
IN-LAB:
Write C++ Program to display all elements of an initialized two dimensional array.
POST LAB TASK:
C++ Program to store temperature of two different cities for a week and display it.
5. 5
LAB 3
IMPLEMENTATION OF STACK
OBJECTIVE:
A program to implement the Stack ADT using arrays.
INTRODUCTION TO STACK:
A stack is an ordered collection of data items into which new items may be inserted and from
which data items may be deleted at one end. Stack is also called Last-In-First-out (LIFO)
lists.
Representation of a Stack
Basic terminology associated with stacks:
1) Stack Pointer (TOP): Keeps track of the current position the stack.
2) Overflow: Occurs when we try to insert (push) more information on a stack than it can
hold.
3) Underflow: Occurs when we try to delete (pop) an item off a stack, which is empty.
Basic Operation Associated with Stacks:
1) Insert (Push) an item into the stack.
2) Delete (Pop) an item from the stack.
1) Procedure PUSH(S, SIZE, TOP, ITEM)
S Array
SIZE Stack size
TOP Stack Pointer
ITEM value in a cell
6. 6
Step 1: {Check for stack overflow}
If TOP==SIZE then
Prints („Stack overflow‟)
Return
Step 2: {Increment pointer top} T
OP=TOP+1
Step 3: {Insert ITEM at top of the Stack}
S [TOP] =ITEM
Return
2) Algorithm for Deletion of an Item from the Stack
S Procedure POP(S, TOP)
S Array TOP
Stack Pointer S
Step 1: {Check for stack underflow}
If TOP==0 then
Prints(„Stack underflow‟)
Return
Step 2: {Return former top element of stack}
ITEM=(S[TOP]);
Step 3: {Decrement pointer TOP} TOP=TOP-1
Prints(„Deleted item is:‟, item);
Return
PRE LAB TASK
Create a stack class and implement the following functions.
1: insertion of values in stack through function calling
2: deletion of values from stack
3: Displaying top element of stack
4: Create is Empty function.
Algorithm to display the items of a Stack S
7. 7
Procedure POP(S, TOP)
S Array
TOP Stack Pointer
Step 1: {Check for stack underflow}
If TOP==0 then
Prints(„stack is empty‟)
Return
Step 2: {display stack elements until TOP value}
Prints(S[TOP])
TOP=TOP+1
POST LAB TASK
Display items of stack using a function „print‟ in stack class.
8. 8
LAB 4
IMPLEMENTATION OF QUEUE
OBJECTIVE:
A C++ program to implement the Queue ADT using arrays.
INTRODUCTION TO QUEUE:
Queue is an ordered collection of data such that the data is inserted at one end and deleted
from other end. It is a collection of items to be processed on a First-In-First-Out(FIFO) or
First Come First Served(FCFS) basics.
Basic Operation Associated on Queues:
1) Insert an item into the Queue.
2) Delete an item into the Queue.
PRE-LAB TASK:
Write a program to insert a value in the queue.
Also implement is empty(), is full() functions.
Implement program in using OOP.
Algorithm to insert an item into a Queue Q:
Procedure Insert(Q, SIZE, F, R, ITEM)
Q Array
SIZE Queue size
F front Pointer
R rear pointer
ITEM: information to be inserted at the rear of queue.
Step 1: {Check for Queue overflow}
9. 9
If R>=SIZE then Prints(„Queue overflow‟)
Return
Step 2: {Increment rear pointer}
R=R+1
Step 3:
{Insert new element at rear end of queue}
Q[R]=ITEM
Step 4: {If initially the queue is empty adjust the front pointer}
If F=0,
then F=1
IN LAB TASK:
Write an object oriented program to implement Dequeue function for a linear queue.
Also print data items of queue.
Algorithm to delete an item from a Queue Q:
Procedure Delete(Q, F, R)
Q Array
F front Pointer
R rear pointer
ITEM: information to be inserted at the rear of queue.
Step 1: {Check for Queue underflow}
If F=0 then
Prints(„Queue underflow‟)
Return
Step 2: {Delete the queue element at front end and store it into item}
ITEM=Q[F]
Step 3: {If queue is empty after deletion, set front and rear pointers to 0}
If F=R then
F=0 R=0 {Otherwise increment front pointer}
Else F=F+1
11. 11
LAB 5
INHERITENCE
OBJECTIVE:
To learn how to inherit class from a base class, accessing public and private members of base
class through functions. Students will be able to learn different types of inheritance and how
it can be used.
INHERITANCE:
New classes inherit some of the properties and behavior of the existing classes. An existing
class that is "parent" of a new class is called a base class. New class that inherits properties
of the base class is called a derived class
Inheritance Syntax:
class deriveclass_name : access_mode base_class_name
{
//body of subclass/derived class
};
Access specifier can be public, protected and private. The default access specifier is private.
Access specifiers affect accessibility of data members of base class from the derived class.
PUBLIC INHERITANCE:
In this the protected member of Base class becomes protected members of Derived class and
public becomes public.
class Derived Class : public Base Class
DERIVED CLASS OF DERIVED CLASSES:
If we are inheriting a derived class using a public inheritance as shown below
class B : public A
class C : public B
then public and protected members of class A will be accessible in class C as public and
protected respectively.
Public Inheritance:
12. 12
In protected mode, the public and protected members of Base class becomes protected
members of Derived class.
class DerivedClass : protected BaseClass
PRIVATE INHERITANCE:
In private mode the public and protected members of Base class become private members of
Derived class.
class DerivedClass : private BaseClass
TYPES OF INHERITANCE:
Single Inheritance:
In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is
inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes. i.e. one sub class is inherited from more than one base classes.
13. 13
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Multilevel Inheritance:
In this type of inheritance, a derived class is created from another derived class.
PRE LAB QUESTION:
Create a class Person that takes information about following.
Name, Age, Gender. Keep these information private.
Implement a function for getting data from user and another for displaying data.
Create object of class person and call both functions from main.
Constructors and Destructors are mandatory for all classes.
IN LAB TASK:
Create a class student that in inherited from the class you created in pre lab.
Class student should have two functions:
1: for getting data from user about student colg-name and subject.
14. 14
2: For displaying data
Call its functions from main.
Try to access any private data member and attach the result (snap shot) of error
relevant to that.
POST LAB TASK.
Create a class Employee that also inherits the class Person at the same time, class
student is also inherited from class Person. Include class student in post lab.
It should take information about Employee id and salary. And display it through
display function.
In Post lab take information for both student and employee and display function
should also be called for both.
The console result should show information of both student and employee at same time.
15. 15
LAB 6
IMPLEMENTATION OF LINKED LIST
OBJECTIVE:
To Implement singly linked list of integers in data structure using functions in Class.
SINGLY LINKED LIST:
Generally a Linked List means "Singly Linked List". It is a chain of records known as Nodes.
Each node has at least two members, one of which points to the next Node in the list and the
other holds the data.
Basically Single Linked Lists are uni-directional as they can only point to the next Node in
the list but not to the previous. We use below structure for a Node in our example.
struct Node {
int Data;
struct Node *Next;
};
Variable Data holds the data in the Node (It can be a pointer variable pointing to the
dynamically allocated memory) while Next holds the address to the next Node in the list.
Head is a pointer variable of type struct Node which acts as the Head to the list. Initially we
set 'Head' as NULL which means list is empty.
Traversing a List, Inserting a Node in the List , Deleting a Node from the List.
DOUBLY LINKED LIST:
A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer,
together with next pointer and data which are there in singly linked list.
16. 16
class node
{
int data;
struct node *next; // Pointer to next node in DLL
struct node *prev; // Pointer to previous node in DLL
};
ADVANTAGES OVER SINGLY LINKED LIST:
1) A DLL can be traversed in both forward and backward direction.
2) The delete operation in DLL is more efficient if pointer to the node to be deleted is given.
In singly linked list, to delete a node, pointer to the previous node is needed. To get this
previous node, sometimes the list is traversed. In DLL, we can get the previous node using
previous pointer.
DISADVANTAGES OVER SINGLY LINKED LIST :
1) Every node of DLL Require extra space for an previous pointer. It is possible to implement
DLL with single pointer though.
2) All operations require an extra pointer previous to be maintained. For example, in
insertion, we need to modify previous pointers together with next pointers. For example in
following functions for insertions at different positions, we need 1 or 2 extra steps to set
previous pointer.
1:Insertion at the front of list
17. 17
2.Insertison in the middle of the list
3: Insertion at the end of the list
PRE LAB
Write Down the Difference between singly Linked List and Doubly Linked List.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
IN-LAB TASK:
Create a class node containing data variables relevant to node of a linked list.
Write two insert functions for a single linked list.
18. 18
1: For insertion and the end of linked list
2: For Insertion at the start of linked List.
Also define the display and delete functions for the linked list sand call from main.
Algorithm creating a new node:
Step 1: if the list is empty
then first==NULL
Step 2: Create a new node
Step 3: Read the content of node using new operator
Step 4: Assign new node link to NULL
cur->link=NULL
Step 5: Assign new node to first & last node
first=cur
last=cur
Step 6: If the list is not empty call insert function
insert ()
Step 7 : Stop
Algorithm for Inserting a new node:
Step 1 : Initialize count c to 1
Step 2 : Create inserting node
cur=(struct node*)malloc(sizeof (struct node));
Step 3: Read the content of node
Step 4: Read the position of insertion
Step 5: Inserting in first position
Check if the pos=1 and
first!=NULL
cur->link=first;
first=cur;
Step 6: Inserting in a given position
next=first;
19. 19
repeat the steps a to c until c < pos
a. prev=next;
b. next=prev->link;
c. c++;
cur->link=prev->link;
prev->link=cur;
Step 7 : Stop
Algorithm for Deleting a node:
Step 1 : Initialize count c to 1
Step 2 : Read the position for deletion
Step 3 : Check if first=NULL print list is empty
Step 4 : If the list contains single element
Check if pos=1 and first->link=NULL
print deleted element is first->data
Step 5 : Assign first to NULL
first=NULL;
Step 6 : If the list contains more than one element and to delete first element
if pos=1 and first->link!=NULL
cur=first;
first=first->link;
cur->link=NULL;
print deleted element is cur->data
free(cur)
Step 7:
If the list contains more than one element and to delete an element at given position
next=first;
repeat the steps a to c until c < pos
a. cur=next;
b. next=next->link;
21. 21
LAB 7
IMPLEMENTATION OF STACKS AND QUEUES USING LINKED LIST.
OBJECTIVE:
Implementation of stacks and queues using Linked List.
PREREQUISITE:
What a stack is.
Implementing stack functionalities using linked lists.
Uses of stacks.
What a queue is.
Implementing queue functionalities using linked lists.
Uses of queues.
LINKED LIST:
A linked list is a data structure that can store an indefinite amount of items. These items are
connected using pointers in a sequential manner.
There are two types of linked list; singly-linked list, and doubly-linked list. In a singly-
linked list, every element contains some data and a link to the next element. On the other
hand, every node in a doubly-linked list contains some data, a link to the next node and a
link to the previous node.
STACK:
A stack is an abstract data type that serves as a collection of elements, with two principal
operations: push, which adds an element to the collection, and pop, which removes the most
recently added element that was not yet removed. The order in which elements come off a
stack gives rise to its alternative name, LIFO (for last in, first out).
22. 22
Node Structure for Stack:
struct node
{
int data;
node *link;
};
Class stack
class stack
{
node *top;
public:
stack() // constructor
{
top=NULL;
}
void push(); // to insert an element
void pop(); // to delete an element
void show(); // to show the stack
};
QUEUE:
A queue is also a linear data structure where insertions and deletions are performed from two
different ends. A new element is added from the rear of the queue and the deletion of existing
elements occurs from the front. Since we can access elements from both ends and the element
inserted first will be the one to be deleted first, the queue is called the 'First in First Out' data
structure (FIFO).
23. 23
Basic Operations:
Enqueue – It specifies the insertion of a new element to the queue. Enqueue will
always take place at the rear end of the queue.
Dequeue – It specifies the deletion of an existing element from the queue. Dequeue
will always take place at the front end of the queue
Structure node for Queue and Class Queue
struct Node
{
int data;
Node *next;
}
Class Queue
{
Public:
Node *front;
Node *Rear;
Public:
//Constructor
EnQueue(){}
Show(){} };
24. 24
PRE LAB: [MARKS 3]
Write function for Dequeue using linked list.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
IN LAB TASK: [MARKS 6]
Implement following functions of stack using linked List.
1: Push 2: Show
Algorithm for Push () in Stack:
Step 1: START
Step 2: Declare a temporary pointer
Step 3: Create a new node using temporary pointer
Step 4: Store integer value sent from main into node‟s data field.
Step 5: If stack is empty, set top pointer equal to new node (i.e. temporary pointer)
Step 6: Set top to be equal to temp->link
Step 7: STOP
Algorithm for Show () in Stack:
Step 1: START
Step 2: Declare a pointer and assign the address of top value to it.
Step 3: Using while condition until pointer is NULL, Display pointer->data.
Step 4: move to next node.
Step 5: STOP
POST LAB TASK: [MARKS 6]
Create a Class Queue and implement its Enqueue and Show function using linked list.
25. 25
LAB 8
BINARY SEARCH TREE
OBJECTIVE:
To implement a binary search tree of characters in data structure using functions.
THEORY:
A binary search tree is a tree where each node has a left and right child. Either child, or both
children, may be missing. Figure 3-2 illustrates a binary search tree. Assuming k represents
the value of a given node, then a binary search tree also has the following property: all
children to the left of the node have values smaller than k, and all children to the right of the
node have values larger than k. The top of a tree is known as the root, and the exposed nodes
at the bottom are known as leaves. Insertion in Binary Search Tree:
1: Check whether root node is present or not(tree available or not). If root is NULL, create
root node.
2: If the element to be inserted is less than the element present in the root node, traverse the
left sub-tree recursively until we reach T->left/T->right is NULL and place the new node at
T->left(key in new node < key in T)/T->right (key in new node > key in T).
3: If the element to be inserted is greater than the element present in root node, traverse the
right sub-tree recursively until we reach T->left/T->right is NULL and place the new node at
T->left/T->right.
Binary search tree deletion
There are three different cases that needs to be considered for deleting a node from binary
search tree.
case 1: Node with no children (or) leaf node
case 2: Node with one child
case 3: Node with two children.
Binary search tree searching
Binary search tree is a tree in which the key value of left child is less than the parent node and
the key value in right child is greater than the root.
1: Check whether the root node is NULL or not. If it's NULL, there is no tree available. So,
return NULL. 2: If node T has the search element, then return that node.
THEORY: Tree Traversals Unlike linear data structures (Array, Linked List, Queues,
Stacks, etc) which have only one logical way to traverse them, trees can be traversed in
different ways. Following are the generally used ways for traversing trees.
26. 26
TREE TRAVERSALS:
(a) In-order (b) Preorder (c) Post-order
IN-ORDER TRAVERSAL:
Algorithm In-order(tree)
1. Traverse the left subtree, i.e., call In-order(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call In-order(right-subtree)
USES OF IN-ORDER
In case of binary search trees (BST), In-order traversal gives nodes in non-decreasing order.
To get nodes of BST in non-increasing order, a variation of In-order traversal where In-order
traversal is reversed, can be used.
PREORDER TRAVERSAL:
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
USES OF PREORDER:
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get
prefix expression on of an expression tree.
POST-ORDER TRAVERSAL:
Algorithm Post-order(tree)
1. Traverse the left subtree, i.e., call Post-order(left-subtree)
2. Traverse the right subtree, i.e., call Post-order(right-subtree)
3. Visit the root.
Uses of Post-order
Post-order traversal is used to delete the tree. Post-order traversal is also useful to get the
postfix expression of an expression tree.
PRE LAB [6]
Create a Binary Search Tree from the values give below.
10,12,5,4,20,8,7,15,13
Write.in-order, pre-order and post order traversal for the tree drawn
27. 27
IN LAB TASK: [5]
Write Insert function to insert character values in Binary Search Tree using Recursive
functions.
POST LAB TASK: [4]
Write display function which displays values of said BST using in-order traversal.
28. 28
LAB 9
IMPLEMENTATION OF BINARY SEARCH ALGORITHM
OBJECTIVE:
Implementation of binary search algorithm in C++.
THEORY:
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search
algorithm works on the principle of divide and conquer. For this algorithm to work properly,
the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned. If the middle item is greater
than the item, then the item is searched in the sub-array to the left of the middle item.
Otherwise, the item is searched for in the sub-array to the right of the middle item. This
process continues on the sub-array as well until the size of the subarray reduces to zero.
PSEUDOCODE:
Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
29. 29
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
PRE LAB TASK:
Write down complexity of linear and binary search in form of asymptotic notation.
IN LAB TASK:
Get an array and a key from the user and find the value in array that matches the key using
binary search.
POST LAB TASK:
Get an array and a key from the user and find the value in array that matches the key using
linear search.
30. 30
LAB 10
IMPLEMENTATION OF SELECTION SORT
OBJECTIVE:
Learn to implement selection sort in C++ to arrange data items.
SELECTION SORT:
Selection sort is a sorting algorithm, specifically an in-place comparison sort.
It has O(n2) time complexity, making it inefficient on large lists
Generally, performs worse than the similar insertion sort.
Selection sort is noted for its simplicity, and also has performance advantages over more
complicated algorithms in certain situations, particularly where auxiliary memory is limited.
The algorithm works as follows:
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)
COMPLEXITY OF SELECTION SORT:
Best Case : O ( n2 )
Average Case : O ( n2 )
Worst Case : O ( n2 )
Algorithm for Selection sort:
Step1: Start
Step2: Declare variables i,j,k,min,temp
Step3: i=0, i<n-1,i++ repeat step3 to step 11
Step4: min=i;
Step 5: for(j=i+1;j<n;j++)
repeat step5 to step 7
Step6: if(a[min]>a[j])
Step7: min=j;
Step8: temp=a[i];
31. 31
Step9: a[i]=a[min];
Step10: a[min]=temp;
Step11: Stop
Algorithm : Main
step1: start
step2: declare i,n,a[10]
step3: Read the size of an array
step4: Read the elements of an array
step5: call sub function
selectionsort (a,n);
step6: print sorted elements of an array a[i]
step7: stop
PRE LAB TASK:
What is stability of a sorting algorithm. Give example.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
_________________________________
IN LAB TASK:
Write C++ program for implementing the Selection sort method to arrange a list of odd
integers between 1 to 21 integers in Descending order.
POST LAB TASK:
Discuss complexity of selection sort algorithm.
32. 32
LAB 11
IMPLEMENTATION OF QUICK SORT
OBJECTIVE:
Write C++ programs for implementing the Quick sort to arrange data items.
QUICK SORT
• It was developed by C.A.R Hoare in 1962.
• Like bubble sort, quick sort is an exchange sort, i.e., items swap positions till the entire
array is sorted. • The quick sort is more efficient because it requires fewer exchanges to
correctly position an element. Basic principle
• Pick one element in the array and rearrange the remaining elements around it. The chosen
element is called the pivot(usually first element of the list).
• Once the pivot is chosen, all the elements lesser than the pivot are moved to the left of the
pivot, and all elements equal to or greater than the pivot are moved to the right of the pivot.
• The pivot acts as a partition dividing the original list into two sub lists, and after the
partitioning, the pivot is in its correct position in the sorted list.
• This procedure of choosing the pivot and partitioning the list is recursively applied to the
sub lists till the subsequent sub lists consists of only one element.
COMPLEXITY OF QUICK SORT:
Best case: O(n log n)
Average case:O(n log n)
Worst case: O(n2)
Algorithm:
void qsort (int a[10], int first, int last)
step 1 : start
step 2 : declare integer variables
i,j,t,pivot,n;
step 3: check up to first less than last
if(first<last) [
step 3 to step 10]
i=first;
j=last;
33. 33
pivot=first;
step 4: repeat upto first less than last from step 4 to step 10
while(i<j)
step 5: repeat 5 to 7
while(a[i]<=a[pivot]&&i<last)
i++;
step 6 : while(a[j]>a[pivot])
j--;
step 7: if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
step 8:
t=a[pivot];
a[pivot]=a[j];
a[j]=t;
step 9: qsort(a,first,j-1);
step 10: qsort(a,j+1,last);
step 11: stop
Algorithm: Main function
step 1: start
step 2: declare i,n,a[10]
step 3: Read the size of an array
step 4: Read the elements of an array
step 5: call sub function qsort(a,0,n-1);
step 6: print sorted elements of an array a[i]
step 7: stop
34. 34
PRE LAB TASK:
Quick sort implementation in C++ using Class.
POST LAB TASK:
Write C program for implementing the Quick sort method to arrange a list of even integers
between 1 to 100 integers in Ascending order.
35. 35
LAB 12
IMPLEMENTATION OF MERGE SORT
OBJECTIVE:
To implements the Merge sort methods to arrange a list of integers in ascending order
MERGE SORT
Merge sort is based on Divide and conquer method. It takes the list to be sorted and divide it
in half to create two unsorted lists. The two unsorted lists are then sorted and merged to get a
sorted list. The two unsorted lists are sorted by continually calling the merge-sort algorithm;
we eventually get a list of size 1 which is already sorted. The two lists of size 1 are then
merged.
Properties:
Best case – When the array is already sorted O(nlogn).
Worst case – When the array is sorted in reverse order O(nlogn).
Average case – O(nlogn).
Extra space is required, so space complexity is O(n) for arrays and O(logn) for linked lists.
Algorithm:
Globally declaring array int a[100]
Algorithm: Merge_Sort(int a[100],int low,int high)
Step1: Start
Step2: Declare an integer middle variable int mid
Step3: Check the condition low less than high
if(low<high) Step4: Initialize mid
mid=(low+high)/2
Step5: call sub_function mergsort from low to middle
Merge_Sort (a,low,mid)
Step6: call sub_function mergsort from middle+1 to high
Merge_Sort (a, mid+1,high)
Step7: call sub_function Merg from low to high
Merge (a,low,high,mid)
Step8: Stop
36. 36
Algorithm: main ()
Step1: Start
Step2: Declare integer variables i, n
Step3: Read the size / no. of elements
Step4: Read the array elements a[i]
Step5: call the sub_function Merge_Sort (a, 0, n-1)
Step6: Print the sorted array: a[i]
Write 4 differences between merge sort and quick sort.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
_________________________________
IN LAB: [5]
Write C++ program for implementing the merge sort method to arrange a list of even integers
between 1 to 100 integers in Descending order.
POST LAB TASK: [5]
Write C program for implementing the Quick sort method to arrange a list of even integers
between 1 to 100 integers in Ascending order.
37. 37
LAB 13
INSERTION SORT ALGORITHM
OBJECTIVE:
Implementation of insertion sort algorithm in C++ to arrange the data items.
INSERTION SORT:
Insertion sort always maintains a sorted sub list in the lower positions of the list. Each new
item is then “inserted” back into the previous sub list such that the sorted sub list is one item
larger.
Example: The following table shows the steps for sorting the sequence
{3, 7, 4, 9, 5, 2, 6, 1}.
In each step, the key under consideration is underlined. The key that was moved (or left in
place because it was biggest yet considered) in the previous step is shown in bold.
3 7 4 9 5 2 6 1
3 7 4 9 5 2 6 1
3 7 4 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 5 7 9 2 6 1
2 3 4 5 7 9 6 1
2 3 4 5 6 7 9 1
1 2 3 4 5 6 7 9
Running Times for Insertion Sort:
Worst case: Θ(n2) Theta(n^2) Θ(n2).
Best case: Θ(n) Theta(n) Θ(n).
Average case for a random array: Θ(n2) Theta(n^2) Θ(n2).
"Almost sorted" case: Θ(n) Theta(n) Θ(n).
Algorithm:
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
38. 38
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
PRELAB TASK:
Discuss worst case and best complexity of insertion sort and compare it with selection sort.
Note: There is no need calculate running time. Just mention the assumed equation for loops
and if conditions only.
IN-LAB TASK:
Write C++ programs for implementing sorting methods to arrange a list of integers in
Ascending order using Insertion sort.
POST LAB TASK:
Write C++ program for implementing the insertion sort method to arrange even positions in
ascending order.
The End