Linked List display and insert at
position
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int data)
{
this -> data = data;
this -> next = NULL;
}
};
void insertAtHead(Node* &head, int d)
{
// new node create
Node* temp = new Node(d);
temp -> next = head;
head = temp;
}
void insertAtTail(Node* &tail, int d)
{
Node* temp = new Node(d);
tail -> next = temp;
tail = temp;
}
void insertAtPosidon(Node* &tail, Node* & head, int posidon, int d) {
//insert at Start
if(posidon == 1)
{
insertAtHead(head, d);
return;
}
Node* temp = head;
int cnt = 1;
while(cnt < posidon-1)
{
temp = temp->next;
cnt++;
}
//inserdng at Last Posidon
if(temp -> next == NULL)
{
insertAtTail(tail,d);
return ;
}
//creadng a node for d
Node* nodeToInsert = new Node(d);
nodeToInsert -> next = temp -> next;
temp -> next = nodeToInsert;
}
void print(Node* &head)
{
if(head == NULL)
{
cout << "List is empty "<< endl;
return ;
}
Node* temp = head;
while(temp != NULL )
{
cout << temp -> data << " ";
temp = temp -> next;
}
cout << endl;
}
int main()
{
Node* node1 = new Node(1);
Node* head = node1;
Node* tail = node1;
for (int i = 2; i <= 10; i++)
{
insertAtTail(tail, i);
}
print(head);
insertAtPosidon(tail,head, 4, 22);
print(head);
}
Queue Enqueue Dequeue
#include <iostream>
using namespace std;
struct Node {
int data;
Node *next;
};
class Queue {
private:
Node *front, *rear;
public:
Queue()
{
front = rear = NULL;
}
void enqueue(int value)
{
Node *temp = new Node;
temp->data = value;
temp->next = NULL;
if (rear == NULL) {
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
void dequeue()
{
Node *temp = front;
if (front == NULL) {
cout << "Queue is empty" << endl;
return;
}
if (front == rear) {
front = rear = NULL;
} else {
front = front->next;
}
delete temp;
}
void display()
{
Node *temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Queue q;
q.enqueue(4);
q.enqueue(1);
q.enqueue(3);
cout << "Elements in queue ajer enqueue: ";
q.display();
q.dequeue();
cout << "Elements in queue ajer first dequeue: ";
q.display();
q.enqueue(8);
cout << "Elements in queue ajer second enqueue: ";
q.display();
q.dequeue();
cout << "Elements in queue ajer second dequeue: ";
q.display();
return 0;
}
Delete Prime Nodes from Stack Using
Linked List
#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node *next;
};
// Function to check if a number is prime
bool isPrime(int x) {
if (x <= 1)
return false;
for (int i = 2; i < x; i++) {
if (x % i == 0)
return false;
}
return true;
}
// Function to delete a node from the stack
Node *deleteNode(Node *head, int x) {
Node *temp = head, *prev = NULL;
if (temp != NULL && temp->data == x)
{
head = temp->next;
delete temp;
return head;
}
while (temp != NULL && temp->data != x)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return head;
prev->next = temp->next;
delete temp;
return head;
}
// FuncMon to delete all prime nodes from the stack
Node *deletePrimes(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
if (isPrime(temp->data))
{
head = deleteNode(head, temp->data);
temp = head;
}
else
{
temp = temp->next;
}
}
return head;
}
// Function to push a node onto the stack
Node *push(Node *head, int x)
{
Node *temp = new Node;
temp->data = x;
temp->next = head;
head = temp;
return head;
}
// Function to print the stack
void printStack(Node *head) {
Node *temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
Node *head = NULL;
head = push(head, 20);
head = push(head, 15);
head = push(head, 19);
head = push(head, 7);
head = push(head, 17);
head = push(head, 11);
cout << "Original Stack: ";
printStack(head);
head = deletePrimes(head);
cout << "Stack after deleting prime nodes: ";
printStack(head);
return 0;
}
Stack using LL
// C++ program to Implement a stack
// using singly linked list
#include <bits/stdc++.h>
using namespace std;
// creating a linked list;
class Node {
public:
int data;
Node* link;
// Constructor
Node(int n)
{
this->data = n;
this->link = NULL;
}
};
class Stack {
Node* top;
public:
Stack() { top = NULL; }
void push(int data)
{
// Create new node temp and allocate memory in heap
Node* temp = new Node(data);
// Check if stack (heap) is full.
// Then inserting an element would
// lead to stack overflow
if (!temp) {
cout << "\nStack Overflow";
exit(1);
}
// Initialize data into temp data field
temp->data = data;
// Put top pointer reference into temp link
temp->link = top;
// Make temp as top of Stack
top = temp;
}
// Utility function to check if
// the stack is empty or not
bool isEmpty()
{
// If top is NULL it means that
// there are no elements are in stack
return top == NULL;
}
// Utility function to return top element in a stack
int peek()
{
// If stack is not empty , return the top element
if (!isEmpty())
return top->data;
else
exit(1);
}
// Function to remove
// a key from given queue q
void pop()
{
Node* temp;
// Check for stack underflow
if (top == NULL) {
cout << "\nStack Underflow" << endl;
exit(1);
}
else {
// Assign top to temp
temp = top;
// Assign second node to top
top = top->link;
// This will automatically destroy
// the link between first node and second node
// Release memory of top node
// i.e delete the node
free(temp);
}
}
// Function to print all the
// elements of the stack
void display()
{
Node* temp;
// Check for stack underflow
if (top == NULL) {
cout << "\nStack Underflow";
exit(1);
}
else {
temp = top;
while (temp != NULL) {
// Print node data
cout << temp->data;
// Assign temp link to temp
temp = temp->link;
if (temp != NULL)
cout << " -> ";
}
}
}
};
// Driven Program
int main()
{
// Creating a stack
Stack s;
// Push the elements of stack
s.push(11);
s.push(22);
s.push(33);
s.push(44);
// Display stack elements
s.display();
// Print top element of stack
cout << "\nTop element is " << s.peek() << endl;
// Delete top elements of stack
s.pop();
s.pop();
// Display stack elements
s.display();
// Print top element of stack
cout << "\nTop element is " << s.peek() << endl;
return 0;
}
Linked List using Queue
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
struct QNode {
int data;
QNode* next;
QNode(int d)
{
data = d;
next = NULL;
}
};
struct Queue {
QNode *front, *rear;
Queue() { front = rear = NULL; }
void enQueue(int x)
{
// Create a new LL node
QNode* temp = new QNode(x);
// If queue is empty, then
// new node is front and rear both
if (rear == NULL) {
front = rear = temp;
return;
}
// Add the new node at
// the end of queue and change rear
rear->next = temp;
rear = temp;
}
// Function to remove
// a key from given queue q
void deQueue()
{
// If queue is empty, return NULL.
if (front == NULL)
return;
// Store previous front and
// move front one node ahead
QNode* temp = front;
front = front->next;
// If front becomes NULL, then
// change rear also as NULL
if (front == NULL)
rear = NULL;
delete (temp);
}
};
// Driver code
int main()
{
Queue q;
q.enQueue(10);
q.enQueue(20);
q.deQueue();
q.deQueue();
q.enQueue(30);
q.enQueue(40);
q.enQueue(50);
q.deQueue();
cout << "Queue Front : " << ((q.front != NULL) ? (q.front)->data : -1)<< endl;
cout << "Queue Rear : " << ((q.rear != NULL) ? (q.rear)->data : -1);
}
Fractional Knapsack
// DARSH GUPTA 20BEC0563
#include<iostream>
#include<algorithm>
using namespace std;
struct Item
{
int value, weight;
double rago;
};
bool compare(Item i1, Item i2)
{
return i1.rago > i2.rago;
}
double fracgonalKnapsack(int W, Item arr[], int n)
{
sort(arr, arr + n, compare);
int curWeight = 0;
double finalValue = 0.0;
for (int i = 0; i < n; i++)
{
if (curWeight + arr[i].weight <= W)
{
curWeight += arr[i].weight;
finalValue += arr[i].value;
}
else
{
int remainingWeight = W - curWeight;
finalValue += arr[i].rago * remainingWeight;
break;
}
}
return finalValue;
}
int main()
{
int W = 60; // Maximum weight the thief can carry
Item arr[] = {{30, 5}, {40, 10}, {45, 15}, {77, 22}, {90, 25}}; // Values and weights of items
int n = sizeof(arr) / sizeof(arr[0]);
for(int i=0; i<n; i++)
arr[i].rago = (double) arr[i].value / arr[i].weight; // Calculate value per unit weight rago
double maxvalue = fracgonalKnapsack(W, arr, n);
cout << "Maximum value that can be carried by the thief: " << maxvalue << endl;
return 0;
}
0/1 Knapsack
/* A Naive recursive implementation of
0-1 Knapsack problem */
#include <bits/stdc++.h>
using namespace std;
// A utility function that returns
// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;
// If weight of the nth item is more
// than Knapsack capacity W, then
// this item cannot be included
// in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
return max(
val[n - 1]
+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
cout << knapSack(W, weight, profit, n);
return 0;
}
// This code is contributed by rathbhupendra
0/1 Knapsack using memoization
// Here is the top-down approach of
// dynamic programming
#include <bits/stdc++.h>
using namespace std;
// Returns the value of maximum profit
int knapSackRec(int W, int wt[], int val[], int i, int** dp)
{
// base condition
if (i < 0)
return 0;
if (dp[i][W] != -1)
return dp[i][W];
if (wt[i] > W) {
// Store the value of function call
// stack in table before return
dp[i][W] = knapSackRec(W, wt, val, i - 1, dp);
return dp[i][W];
}
else {
// Store value in a table before return
dp[i][W] = max(val[i]
+ knapSackRec(W - wt[i], wt, val,
i - 1, dp),
knapSackRec(W, wt, val, i - 1, dp));
// Return value of table after storing
return dp[i][W];
}
}
int knapSack(int W, int wt[], int val[], int n)
{
// double pointer to declare the
// table dynamically
int** dp;
dp = new int*[n];
// loop to create the table dynamically
for (int i = 0; i < n; i++)
dp[i] = new int[W + 1];
// loop to initially filled the
// table with -1
for (int i = 0; i < n; i++)
for (int j = 0; j < W + 1; j++)
dp[i][j] = -1;
return knapSackRec(W, wt, val, n - 1, dp);
}
// Driver Code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
cout << knapSack(W, weight, profit, n);
return 0;
}
Minimum Spanning Tree using Primes
Algo
// A C++ program for Prim's Minimum
// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representa4on of the graph
#include <bits/stdc++.h>
using namespace std;
// Number of ver4ces in the graph
#define V 9
// A u4lity func4on to find the vertex with
// minimum key value, from the set of ver4ces
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Ini4alize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
// A utlity func4on to print the
// constructed MST stored in parent[]
void printMST(int parent[], int graph[V][V])
{
cout << "Edge \tWeight\n";
for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << " \t"
<< graph[i][parent[i]] << " \n";
}
// Func4on to construct and print MST for
// a graph represented using adjacency
// matrix representa4on
void primMST(int graph[V][V])
{
// Array to store constructed MST
int parent[V];
// Key values used to pick minimum weight edge in cut
int key[V];
// To represent set of ver4ces included in MST
bool mstSet[V];
// Ini4alize all keys as INFINITE
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
// Always include first 1st vertex in MST.
// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;
// First node is always root of MST
parent[0] = -1;
// The MST will have V ver4ces
for (int count = 0; count < V - 1; count++)
{
// Pick the minimum key vertex from the
// set of ver4ces not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of
// the adjacent ver4ces of the picked vertex.
// Consider only those ver4ces which are not
// yet included in MST
for (int v = 0; v < V; v++)
// graph[u][v] is non zero only for adjacent
// ver4ces of m mstSet[v] is false for ver4ces
// not yet included in MST Update the key only
// if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
&& graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
// Print the constructed MST
printMST(parent, graph);
}
// Driver's code
int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0},
{ 0, 8, 0, 7, 0, 4, 0, 0, 2},
{ 0, 0, 7, 0, 9, 14, 0, 0, 0},
{ 0, 0, 0, 9, 0, 10, 0, 0, 0},
{ 0, 0, 4, 14, 10, 0, 2, 0, 0},
{ 0, 0, 0, 0, 0, 2, 0 , 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{ 0, 0, 2, 0, 0, 0, 6, 7, 0}
};
// Print the solu4on
primMST(graph);
return 0;
}
Binary Tree Traversal Preorder, Post
order, in
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
Node (int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
Node* insert (Node * node, int data)
{
if (node == NULL)
{
return new Node (data);
}
if (data <= node->data)
{
node->left = insert (node->left, data);
}
else
{
node->right = insert (node->right, data);
}
return node;
}
void preOrder (Node * root)
{
if (root != NULL)
{
cout << root->data << " ";
preOrder (root->left);
preOrder (root->right);
}
}
void inOrder (Node * root)
{
if (root != NULL)
{
inOrder (root->left);
cout << root->data << " ";
inOrder (root->right);
}
}
void postOrder (Node * root)
{
if (root != NULL)
{
postOrder (root->left);
postOrder (root->right);
cout << root->data << " ";
}
}
int main ()
{
Node *root = NULL;
int data[] = { 14, 12, 3, 5, 9, 7, 5, 4, 12, 13, 22 };
int n = sizeof (data) / sizeof (data[0]);
for (int i = 0; i < n; i++)
{
root = insert (root, data[i]);
}
cout << "Pre-Order Traversal of the binary tree: " << endl;
preOrder (root);
cout << endl;
cout << "In-Order Traversal of the binary tree: " << endl;
inOrder (root);
cout << endl;
cout << "Post-Order Traversal of the binary tree: " << endl;
postOrder (root);
cout << endl;
return 0;
}
BST Deletion
// 20BEC0563 DARSH GUPTA
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *leR;
Node *right;
Node(int data) {
this->data = data;
this->leR = NULL;
this->right = NULL;
}
};
Node *insert(Node *root, int data) {
if (root == NULL) {
return new Node(data);
}
if (data <= root->data) {
root->leR = insert(root->leR, data);
} else {
root->right = insert(root->right, data);
}
return root;
}
Node *findMinNode(Node *root) {
while (root->leR != NULL) {
root = root->leR;
}
return root;
}
Node *deleteNode(Node *root, int data) {
if (root == NULL) {
return root;
}
if (data < root->data) {
root->leR = deleteNode(root->leR, data);
}
else if (data > root->data) {
root->right = deleteNode(root->right, data);
}
else {
if (root->leR == NULL) {
Node *temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
Node *temp = root->leR;
delete root;
return temp;
}
else {
Node *temp = findMinNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
}
return root;
}
void inOrder(Node *root) {
if (root != NULL) {
inOrder(root->leR);
cout << root->data << " ";
inOrder(root->right);
}
}
int main() {
Node *root = NULL;
int data[] = {11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31};
int n = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < n; i++) {
root = insert(root, data[i]);
}
cout << "Binary Search Tree: ";
inOrder(root);
cout << endl;
cout << "ARer deledng 19: ";
root = deleteNode(root, 19);
inOrder(root);
cout << endl;
cout << "ARer deledng 11: ";
root = deleteNode(root, 11);
inOrder(root);
cout << endl;
cout << "ARer deledng 5: ";
root = deleteNode(root, 5);
inOrder(root);
cout << endl;
return 0;
}
BST from given pre order traversal
#include <iostream>
#include <stack>
using namespace std;
struct Node {
int data;
Node* leR;
Node* right;
};
Node* newNode(int data) {
Node* node = new Node;
node->data = data;
node->leR = node->right = NULL;
return node;
}
Node* construct_bst(int pre[], int& preIndex, int low, int high, int size) {
if (preIndex >= size || low > high) {
return NULL;
}
Node* root = newNode(pre[preIndex]);
preIndex++;
if (low == high) {
return root;
}
int i;
for (i = low; i <= high; i++) {
if (pre[i] > root->data) {
break;
}
}
root->leR = construct_bst(pre, preIndex, preIndex, i - 1, size);
root->right = construct_bst(pre, preIndex, i, high, size);
return root;
}
void preOrder(Node* node) {
if (node == NULL) {
return;
}
cout << node->data << " ";
preOrder(node->leR);
preOrder(node->right);
}
int main() {
int pre[] = {30, 20, 10, 15, 25, 23, 39, 35, 42};
int size = sizeof(pre) / sizeof(pre[0]);
int preIndex = 0;
Node* root = construct_bst(pre, preIndex, 0, size - 1, size);
cout << "Preorder traversal of the constructed BST: ";
preOrder(root);
return 0;
}
BST from given post order traversal
/* A O(n) program for construction of
BST from postorder traversal */
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct node
{
int data;
struct node *left, *right;
};
// A utility function to create a node
struct node* newNode (int data)
{
struct node* temp =
(struct node *) malloc(sizeof(struct node));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A recursive function to construct
// BST from post[]. postIndex is used
// to keep track of index in post[].
struct node* constructTreeUtil(int post[], int* postIndex,
int key, int min, int max,
int size)
{
// Base case
if (*postIndex < 0)
return NULL;
struct node* root = NULL;
// If current element of post[] is
// in range, then only it is part
// of current subtree
if (key > min && key < max)
{
// Allocate memory for root of this
// subtree and decrement *postIndex
root = newNode(key);
*postIndex = *postIndex - 1;
if (*postIndex >= 0)
{
// All nodes which are in range {key..max}
// will go in right subtree, and first such
// node will be root of right subtree.
root->right = constructTreeUtil(post, postIndex,
post[*postIndex],
key, max, size );
// Construct the subtree under root
// All nodes which are in range {min .. key}
// will go in left subtree, and first such
// node will be root of left subtree.
root->left = constructTreeUtil(post, postIndex,
post[*postIndex],
min, key, size );
}
}
return root;
}
// The main function to construct BST
// from given postorder traversal.
// This function mainly uses constructTreeUtil()
struct node *constructTree (int post[],
int size)
{
int postIndex = size-1;
return constructTreeUtil(post, &postIndex,
post[postIndex],
INT_MIN, INT_MAX, size);
}
// A utility function to print
// inorder traversal of a Binary Tree
void printInorder (struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
// Driver Code
int main ()
{
int post[] = {1, 7, 5, 50, 40, 10};
int size = sizeof(post) / sizeof(post[0]);
struct node *root = constructTree(post, size);
cout << "Inorder traversal of "
<< "the constructed tree: \n";
printInorder(root);
return 0;
}
// This code is contributed
// by Akanksha Rai
BST from given in order traversal
/* C++ program to construct tree
from inorder traversal */
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
class node
{
public:
int data;
node* left;
node* right;
};
/* Prototypes of a utility function to get the maximum
value in inorder[start..end] */
int max(int inorder[], int strt, int end);
/* A utility function to allocate memory for a node */
node* newNode(int data);
/* Recursive function to construct binary of size len from
Inorder traversal inorder[]. Initial values of start and end
should be 0 and len -1. */
node* buildTree (int inorder[], int start, int end)
{
if (start > end)
return NULL;
/* Find index of the maximum element from Binary Tree */
int i = max (inorder, start, end);
/* Pick the maximum value and make it root */
node *root = newNode(inorder[i]);
/* If this is the only element in inorder[start..end],
then return it */
if (start == end)
return root;
/* Using index in Inorder traversal, construct left and
right subtress */
root->left = buildTree (inorder, start, i - 1);
root->right = buildTree (inorder, i + 1, end);
return root;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the maximum value in arr[start...end] */
int max (int arr[], int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for(i = strt + 1; i <= end; i++)
{
if(arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode (int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return Node;
}
/* This function is here just to test buildTree() */
void printInorder (node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder (node->left);
/* then print the data of node */
cout<<node->data<<" ";
/* now recur on right child */
printInorder (node->right);
}
/* Driver code*/
int main()
{
/* Assume that inorder traversal of following tree is given
40
/\
10 30
/ \
5 28 */
int inorder[] = {5, 10, 40, 30, 28};
int len = sizeof(inorder)/sizeof(inorder[0]);
node *root = buildTree(inorder, 0, len - 1);
/* Let us test the built tree by printing Inorder traversal */
cout << "Inorder traversal of the constructed tree is \n";
printInorder(root);
return 0;
}
Caesar Cipher
// DARSH GUPTA 20BEC0563
// CAESAR CIPHER
#include <iostream>
using namespace std;
string encrypt(string text, int shiM)
{
string result = "";
for (int i = 0; i < text.length(); i++)
{
if (isupper(text[i]))
result += char(int(text[i] + shiM - 65) % 26 + 65);
else
result += char(int(text[i] + shiM - 97) % 26 + 97);
}
return result;
}
int main()
{
string text;
int shiM;
cout << "Enter the text to be encrypted: ";
cin >> text;
cout << endl;
cout << "Enter the shiM: ";
cin >> shiM;
cout << "Cipher text is: " << encrypt(text, shiM);
return 0;
}
Insertion Sort
// C++ program for insertion sort
// Darsh Gupta 20BEC0563
#include <iostream>
using namespace std;
// Function to sort an array using inser6on sort
void inser6onSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1],
// that are greater than key, to one
// posi6on ahead of their
// current posi6on
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// print the Array
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {4,3,2,10,12,1,5,6};
int N = sizeof(arr) / sizeof(arr[0]);
inser6onSort(arr, N);
printArray(arr, N);
return 0;
}
Merge Sort
// Merge sort in C++
#include <iostream>
using namespace std;
// Merge two subarrays L and M into arr
void merge(int arr[], int p, int q, int r) {
// Create L ← A[p..q] and M ← A[q+1..r]
int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
// Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = p;
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Merge the sorted subarrays
merge(arr, l, m, r);
}
}
// Print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
cout << "Sorted array: \n";
printArray(arr, size);
return 0;
}
Bubble Sort
// Optimized implementation of Bubble sort
#include <bits/stdc++.h>
using namespace std;
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped
// by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout <<" "<< arr[i];
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int N = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, N);
cout <<"Sorted array: \n";
printArray(arr, N);
return 0;
}
Quick Sort
// DARSH GUPTA 20BEC0563
#include<iostream>
using namespace std;
int par66on( int arr[], int s, int e) {
int pivot = arr[s];
int cnt = 0;
for(int i = s+1; i<=e; i++) {
if(arr[i] <=pivot) {
cnt++;
}
}
//place pivot at right posi6on
int pivotIndex = s + cnt;
swap(arr[pivotIndex], arr[s]);
//leZ and right wala part smbhal lete h
int i = s, j = e;
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 s, int e) {
//base case
if(s >= e)
return ;
//perform par66on
int p = par66on(arr, s, e);
//Sort leZ part
quickSort(arr, s, p-1);
//Sort Right Part
quickSort(arr, p+1, e);
}
int main() {
int arr[8] = {2,7,3,9,1,6,8,4};
int n = 8;
quickSort(arr, 0, n-1);
for(int i=0; i<n; i++)
{
cout << arr[i] << " ";
} cout << endl;
return 0;
}
BFS Graphs
// Program to print BFS traversal from a given
// source vertex. BFS(int s) traverses ver4ces
// reachable from s.
#include <bits/stdc++.h>
using namespace std;
// This class represents a directed graph using
// adjacency list representaton
class Graph {
int V; // No. of ver4ces
// Pointer to an array containing adjacency
// lists
vector<list<int> > adj;
public:
Graph(int V); // Constructor
// func4on to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the ver4ces as not visited
vector<bool> visited;
visited.resize(V, false);
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
while (!queue.empty()) {
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent ver4ces of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjacent : adj[s])
{
if (!visited[adjacent]) {
visited[adjacent] = true;
queue.push_back(adjacent);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(star4ng from vertex 2) \n";
g.BFS(2);
return 0;
}
Postfix Using Stack
// C++ program to evaluate value of a postfix expression
#include <bits/stdc++.h>
using namespace std;
// The main function that returns value
// of a given postfix expression
int evaluatePostfix(string exp)
{
// Create a stack of capacity equal to expression size
stack<int> st;
// Scan all characters one by one
for (int i = 0; i < exp.size(); ++i) {
// If the scanned character is an operand
// (number here), push it to the stack.
if (isdigit(exp[i]))
st.push(exp[i] - '0');
// If the scanned character is an operator,
// pop two elements from stack apply the operator
else {
int val1 = st.top();
st.pop();
int val2 = st.top();
st.pop();
switch (exp[i]) {
case '+':
st.push(val2 + val1);
break;
case '-':
st.push(val2 - val1);
break;
case '*':
st.push(val2 * val1);
break;
case '/':
st.push(val2 / val1);
break;
}
}
}
return st.top();
}
// Driver code
int main()
{
string exp = "231*+9-";
// Function call
cout << "postfix evaluation: " << evaluatePostfix(exp);
return 0;
}
Dijkstras Algo
// C++ program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representa4on of the graph
#include <iostream>
using namespace std;
#include <limits.h>
// Number of ver4ces in the graph
#define V 9
// A u4lity func4on to find the vertex with minimum
// distance value, from the set of ver4ces not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Ini4alize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A u4lity func4on to print the constructed distance
// array
void printSolu4on(int dist[])
{
cout << "Vertex \t Distance from Source" << endl;
for (int i = 0; i < V; i++)
{
char c = i + '0' + 17;
cout << c << " \t\t\t\t" << dist[i] << endl;
}
}
// Func4on that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representa4on
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i
bool sptSet[V]; // sptSet[i] will be true if vertex i is
// included in shortest
// path tree or shortest distance from src to i is
// finalized
// Ini4alize all distances as INFINITE and stpSet[] as
// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all ver4ces
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// ver4ces not yet processed. u is always equal to
// src in the first itera4on.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent ver4ces of the
// picked vertex.
for (int v = 0; v < V; v++)
// Update dist[v] only if is not in sptSet,
// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// print the constructed distance array
printSolu4on(dist);
}
// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 5, 7, 0, 0, 0, 0, 0, 0 },
{ 5, 0, 10, 4, 0, 0, 17, 0, 0},
{ 7, 10, 0, 3, 15, 0, 0, 0, 0},
{ 0, 4, 3, 0, 1, 0, 0, 0, 0},
{ 0, 0, 15, 1, 0, 3, 0, 0, 0},
{ 0, 0, 0, 0, 3, 0, 2, 0, 0},
{ 0, 17, 0, 0, 0, 2, 0, 15, 4},
{ 0, 0, 0, 0, 0, 0, 15, 0, 2},
{ 0, 0, 0, 0, 0, 0, 4, 2, 0 }
};
// Func4on call
dijkstra(graph, 0);
return 0;
}