0% found this document useful (0 votes)
15 views24 pages

pgm1 8

The document contains multiple C++ programs demonstrating various data structures and algorithms, including Tower of Hanoi, binary search tree traversal, stack operations using linked lists, circular queue operations, quicksort, heapsort, and the knapsack problem using a greedy method. Each program includes code snippets, expected outputs, and explanations of time complexity and auxiliary space where applicable. The programs serve as practical examples for learning and implementing fundamental algorithms and data structures in C++.

Uploaded by

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

pgm1 8

The document contains multiple C++ programs demonstrating various data structures and algorithms, including Tower of Hanoi, binary search tree traversal, stack operations using linked lists, circular queue operations, quicksort, heapsort, and the knapsack problem using a greedy method. Each program includes code snippets, expected outputs, and explanations of time complexity and auxiliary space where applicable. The programs serve as practical examples for learning and implementing fundamental algorithms and data structures in C++.

Uploaded by

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

1.

write a program to solve the tower of hanoi using recursion in


C++

#include <iostream.h>
void towerOfHanoi(int n, char from_rod, char to_rod,
char aux_rod)
{
if (n == 0) {
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from rod " << from_rod
<< " to rod " << to_rod << endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}

int main()
{
int N = 3;
towerOfHanoi(N, 'A', 'C', 'B');
return 0;
}
Output
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Time complexity: O(2N), There are two possibilities for every disk. Therefore, 2
* 2 * 2 * . . . * 2(N times) is 2 N
Auxiliary Space: O(N), Function call stack space
2. write a program to traverse through binary search tree using
traversals in C++

#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root);
return 0;
}
Output
In-Order traversal of the Binary Search Tree is: 1 2 3 4 5 9

3. write a program to perform various operations on stack using


linked list in c++
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* top = NULL;
void push(int val) {
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = val;
newnode->next = top;
top = newnode;
}
void pop() {
if(top==NULL)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< top->data <<endl;
top = top->next;
}
}
void display() {
struct Node* ptr;
if(top==NULL)
cout<<"stack is empty";
else {
ptr = top;
cout<<"Stack elements are: ";
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
Output
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
4. write a program to perform various operations in circular queue in
c++
#include <iostream>
int cqueue[5];
int front = -1, rear = -1, n=5;
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
} else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void deleteCQ() {
if (front == -1) {
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;

if (front == rear) {
front = -1;
rear = -1;
} else {
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {

int ch, val;


cout<<"1)Insert\n";
cout<<"2)Delete\n";
cout<<"3)Display\n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1:
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val);
break;

case 2:
deleteCQ();
break;

case 3:
displayCQ();
break;

case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}

Output
The output of the above program is as follows −

1)Insert
2)Delete
3)Display
4)Exit

Enter choice : 1
Input for insertion:
Enter choice : 1
Input for insertion:
Enter choice : 1
Input for insertion:
Enter choice : 1
Input for insertion:
Enter choice : 1
Input for insertion:
Enter choice : 2
Element deleted from queue is : 5
Enter choice : 2
Element deleted from queue is : 3
Enter choice : 2
Element deleted from queue is : 2
Enter choice : 1
Input for insertion: 6
Enter choice : 3
Queue elements are :
796
Enter choice : 4
Exit

4.write a program to perform various operations in circular queue in


c++

#include<bits/stdc++.h>
using namespace std;
struct Queue
{

// Initialize front and rear


int rear, front;

// Circular Queue
int size;

int *arr;

Queue (int s){


front = rear = -1;
size = s;
arr = new int[s];
}

void enQueue (int value);

int deQueue ();

void displayQueue ();

};

/* Function to create Circular queue */


void Queue::enQueue (int value)
{
if ((front == 0 && rear == size - 1) || (rear == (front - 1) % (size - 1)))
{
cout << "\nQueue is Full";
return;
}

else if (front == -1) /* Insert First Element */


{
front = rear = 0;
arr[rear] = value;
}

else if (rear == size - 1 && front != 0)


{
rear = 0;
arr[rear] = value;
}

else{
rear++;
arr[rear] = value;
}
}

// Function to delete element from Circular Queue


int Queue::deQueue ()
{
if (front == -1)
{
cout << "\nQueue is Empty";
return INT_MIN;
}

int data = arr[front];


arr[front] = -1;

if (front == rear)
{
front = -1;
rear = -1;
}

else if (front == size - 1)


front = 0;

else
front++;

return data;

// Function displaying the elements


// of Circular Queue
void Queue::displayQueue ()
{
if (front == -1)
{
cout << "\nQueue is Empty";
return;
}

cout << "\nElements in Circular Queue are: ";

if (rear >= front)


{
for (int i = front; i <= rear; i++)
cout<<arr[i]<<" ";
}

else
{
for (int i = front; i < size; i++)
cout<<arr[i]<<" ";

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


cout<<arr[i]<<" ";
}
}

int main ()
{
Queue q (5);

// Inserting elements in Circular Queue


q.enQueue (10);
q.enQueue (20);
q.enQueue (30);
q.enQueue (40);

// Display elements present in Circular Queue


q.displayQueue ();

// Deleting elements from Circular Queue


cout << "\nDeleted value = " << q.deQueue ();
cout << "\nDeleted value = " << q.deQueue ();

q.displayQueue ();

q.enQueue (50);
q.enQueue (60);
q.enQueue (70);

q.displayQueue ();

return 0;

}
Output:

Elements in circular queue are : 10 20 30 40

Deleted element = 10

Deleted element =20

Elements in circular queue are : 30 40

Elements in circular queue are : 30 40 50 60 70


5. write a program to sort an array using quick sort in c++
#include <iostream.h>
int partition(int arr[], int start, int end)
{

int pivot = arr[start];

int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i] <= pivot)
count++;
}

// Giving pivot element its correct position


int pivotIndex = start + count;
swap(arr[pivotIndex], arr[start]);

// Sorting left and right parts of the pivot element


int i = start, j = end;

while (i < pivotIndex && j > pivotIndex) {

while (arr[i] <= pivot) {


i++;
}

while (arr[j] > pivot) {


j--;
}

if (i < pivotIndex && j > pivotIndex) {


swap(arr[i++], arr[j--]);
}
}

return pivotIndex;
}
void quickSort(int arr[], int start, int end)
{

// base case
if (start >= end)
return;

// partitioning the array


int p = partition(arr, start, end);

// Sorting the left part


quickSort(arr, start, p - 1);

// Sorting the right part


quickSort(arr, p + 1, end);
}

int main()
{

int arr[] = { 9, 3, 4, 2, 1, 8 };
int n = 6;

quickSort(arr, 0, n - 1);

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


cout << arr[i] << " ";
}

return 0;
}

Output
123489
6. write a program to solve number of elements in ascending order
using heapsort
#include <iostream>

void heapify(int arr[], int n, int i)


{
int largest = i; // Initialize largest as root Since we are using 0 based
indexing
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger than largest so far


if (r < n && arr[r] > arr[largest])
largest = r;

// If largest is not root


if (largest != i) {
swap(arr[i], arr[largest]);

// Recursively heapify the affected sub-tree


heapify(arr, n, largest);
}
}

// main function to do heap sort


void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// One by one extract an element from heap


for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);

// call max heapify on the reduced heap


heapify(arr, i, 0);
}
}

/* A utility function to print array of size n */


void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}

// Driver program
int main()
{
int arr[] = { 60 ,20 ,40 ,70, 30, 10};
int n = sizeof(arr) / sizeof(arr[0]);
//heapify algorithm
// the loop must go reverse you will get after analyzing manually
// (i=n/2 -1) because other nodes/ ele's are leaf nodes
// (i=n/2 -1) for 0 based indexing
// (i=n/2) for 1 based indexing
for(int i=n/2 -1;i>=0;i--){
heapify(arr,n,i);
}

cout << "After heapifying array is \n";


printArray(arr, n);

heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);

return 0;
}

Output
After heapifying array is
70 60 40 20 30 10
Sorted array is
10 20 30 40 60 70

note
Time complexity : O(N*logN)
Auxiliary space: O(1)

7. Write a program to solve the knap sack problem using greedy method
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct {
int v;
int w;
float d;
} Item;
void input(Item items[],int sizeOfItems) {
cout << "Enter total "<< sizeOfItems <<" item's values and weight" <<
endl;
for(int i = 0; i < sizeOfItems; i++) {
cout << "Enter "<< i+1 << " V ";
cin >> items[i].v;
cout << "Enter "<< i+1 << " W ";
cin >> items[i].w;
}
}
void display(Item items[], int sizeOfItems) {
int i;
cout << "values: ";
for(i = 0; i < sizeOfItems; i++) {
cout << items[i].v << "\t";
}
cout << endl << "weight: ";
for (i = 0; i < sizeOfItems; i++) {
cout << items[i].w << "\t";
}
cout << endl;
}
bool compare(Item i1, Item i2) {
return (i1.d > i2.d);
}
float knapsack(Item items[], int sizeOfItems, int W) {
int i, j;
float totalValue = 0, totalWeight = 0;
for (i = 0; i < sizeOfItems; i++) {
items[i].d = (float)items[i].v / items[i].w; //typecasting done (v is int
and w is also int so we get final value of d as int)
}
sort(items, items+sizeOfItems, compare);
/*
uncomment if u need to check the data after sortingis done
cout << "values : ";
for(i = 0; i < sizeOfItems; i++) {
cout << items[i].v << "\t";
}
cout << endl << "weights: ";
for (i = 0; i < sizeOfItems; i++) {
cout << items[i].w << "\t";
}
cout << endl << "ratio : ";
for (i = 0; i < sizeOfItems; i++) {
cout << items[i].d << "\t";
}
cout << endl;
*/
for(i=0; i<sizeOfItems; i++) {
if(totalWeight + items[i].w<= W) {
totalValue += items[i].v ;
totalWeight += items[i].w;
} else {
int wt = W-totalWeight;
totalValue += (wt * items[i].d);
totalWeight += wt;
break;
}
}
cout << "Total weight in bag " << totalWeight<<endl;
return totalValue;
}
int main() {
int W;
Item items[4];
input(items, 4);
cout << "Entered data \n";
display(items,4);
cout<< "Enter Knapsack weight \n";
cin >> W;
float mxVal = knapsack(items, 4, W);
cout << "Max value for "<< W <<" weight is "<< mxVal;
}

Enter total 4 item's values and weight


Enter 1 V Enter 1 W Enter 2 V Enter 2 W Enter 3 V Enter 3 W Enter 4 V Enter 4 W Entered data
values: 2 0 0 0
weight: 0 490642064 0 4196544
Enter Knapsack weight
Total weight in bag 0
Max value for 0 weight is 2

7.. Write a program to solve the knap sack problem using greedy method

#include <bits/stdc++.h>
using namespace std;

// Function to find maximum profit


void maxProfit(vector<int> profit,
vector<int> weight, int N)
{

// Number of total weights present


int numOfElements = profit.size();
int i;

// Multimap container to store


// ratio and index
multimap<double, int> ratio;

// Variable to store maximum profit


double max_profit = 0;
for (i = 0; i < numOfElements; i++) {
// Insert ratio profit[i] / weight[i]
// and corresponding index
ratio.insert(make_pair(
(double)profit[i] / weight[i], i));
}

// Declare a reverse iterator


// for Multimap
multimap<double, int>::reverse_iterator it;

// Traverse the map in reverse order


for (it = ratio.rbegin(); it != ratio.rend();
it++) {

// Fraction of weight of i'th item


// that can be kept in knapsack
double fraction = (double)N / weight[it->second];

// if remaining_weight is greater
// than the weight of i'th item
if (N >= 0
&& N >= weight[it->second]) {

// increase max_profit by i'th


// profit value
max_profit += profit[it->second];

// decrement knapsack to form


// new remaining_weight
N -= weight[it->second];
}

// remaining_weight less than


// weight of i'th item
else if (N < weight[it->second]) {
max_profit += fraction
* profit[it->second];
break;
}
}

// Print the maximum profit earned


cout << "Maximum profit earned is:"
<< max_profit;
}

// Driver Code
int main()
{
// Size of list
int size = 4;

// Given profit and weight


vector<int> profit(size), weight(size);

// Profit of items
profit[0] = 100, profit[1] = 280,
profit[2] = 120, profit[3] = 120;

// Weight of items
weight[0] = 10, weight[1] = 40,
weight[2] = 20, weight[3] = 24;

// Capacity of knapsack
int N = 60;

// Function Call
maxProfit(profit, weight, N);
}
Output:
Maximum profit earned is:440

Note
Time Complexity: O(N)
Auxiliary Space: O(N)

Write a program to search for an element in a tree using divide and conquer
#include<bits/stdc++.h>

using namespace std;

int Binary_search(int arr[],int l,int r, int key)

{
if(l<=r)
{
int mid = l+((r-l)/2);

if(arr[mid]==key)
return 1;

else if(arr[mid]>key)
return Binary_search(arr,l,mid-1,key);

else
return Binary_search(arr,mid+1,r,key);
}

return 0;
}
int main()
{
int arr[]={3,4,5,6,7,8,4,5,2,8,9,13,14,17,19};

int n=sizeof(arr)/sizeof(arr[0]);

int key=79;

sort(arr,arr+n);

if(Binary_search(arr,0,n-1,key))
cout<<"key is found in given array"<<endl;

else
cout<<"key is not found in given array"<<endl;
}

Output
2 3 4 4 5 5 6 7 8 8 9 13 14 17 19

You might also like