0% found this document useful (0 votes)
32 views35 pages

Data Structure With C++

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)
32 views35 pages

Data Structure With C++

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/ 35

1.

Implementation of Sorting Techniques


i. Bubble Sort

#include <stdio.h>

int main() {

int arr[7], n = 7, i, j;

// Input from the user

printf("Enter 7 numbers:\n");

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

scanf("%d", &arr[i]);

// Bubble Sort Algorithm

for (i = 0; i < n - 1; i++) {

for (j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap elements

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

// Display the sorted array

printf("Sorted array: ");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

}
ii. Insertion Sort

#include<stdio.h>

int main() {

int arr[7], i, j, key;

printf("Enter 7 numbers:\n");

for (i = 0; i < 7; i++) scanf("%d", &arr[i]);

for (i = 1; i < 7; i++) {

key = arr[i];

for (j = i - 1; j >= 0 && arr[j] > key; j--)

arr[j + 1] = arr[j];

arr[j + 1] = key;

printf("Sorted array: ");

for (i = 0; i < 7; i++) printf("%d ", arr[i]);

return 0;

}
2. Implementation of Searching Techniques
i. Linear Search

#include <stdio.h>

int main() {

int arr[7], n = 7, i, key, found = 0;

// Input from the user

printf("Enter 7 numbers:\n");

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

scanf("%d", &arr[i]);

// Input the key to search for

printf("Enter the number to search: ");

scanf("%d", &key);

// Linear Search Algorithm

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

if (arr[i] == key) {

printf("Element %d found at index %d.\n", key, i);

found = 1;

break; // Exit the loop once the element is found

// If the element is not found

if (!found) {

printf("Element %d not found in the array.\n", key);

return 0;

}
ii. Binary Search

#include <stdio.h>

int main() {

int arr[7], n = 5, key, left = 0, right = n - 1, mid;

int i; // Declare variables outside the loop

// Input sorted array

printf("Enter 5 sorted numbers:\n");

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

scanf("%d", &arr[i]);

// Input the key to search for

printf("Enter the number to search: ");

scanf("%d", &key);

// Binary Search

while (left <= right) {

mid = left + (right - left) / 2;

if (arr[mid] == key) {

printf("Element %d found at index %d.\n", key, mid);

return 0; // Exit if found

if (arr[mid] < key)

left = mid + 1; // Move to right half

else

right = mid - 1; // Move to left half

// If not found

printf("Element %d
not found in the
array.\n", key);

return 0;

}
3. Implement program for Modulo Division as hashing method.

#include <stdio.h>

#define TABLE_SIZE 5

void insert(int table[], int key) {

int index = key % TABLE_SIZE;

if (table[index] == -1)

table[index] = key;

else

printf("Collision at index %d for key %d.\n", index, key);

void display(int table[]) {

printf("\nHash Table:\n");

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

if (table[i] != -1)

printf("Index %d: %d\n", i, table[i]);

else

printf("Index %d: EMPTY\n", i);

int main() {

int table[TABLE_SIZE], keys[] = {25, 37, 18, 55, 42};

size_t i; // Change i to size_t

for (i = 0; i < TABLE_SIZE; i++)

table[i] = -1;

for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++)

insert(table, keys[i]);

display(table);

return 0;

}
4. Implementation of Singly Linked List.

#include <iostream>

using namespace std;

// Node structure

struct Node {

int data; // Data part

Node* next; // Pointer to the next node

};

// Singly Linked List class

class SinglyLinkedList {

private:

Node* head;

public:

// Constructor to initialize the list with an empty head

SinglyLinkedList() {

head = nullptr;

// Function to insert a new node at the end

void insertEnd(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = nullptr;

// If the list is empty, make the new node the head

if (head == nullptr) {

head = newNode;

} else {

Node* temp = head;

// Traverse to the last node

while (temp->next != nullptr) {

temp = temp->next;

temp->next = newNode;

}
}

// Function to insert a new node at the beginning

void insertBegin(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = head;

head = newNode;

// Function to delete a node with a given value

void deleteNode(int value) {

if (head == nullptr) {

cout << "List is empty!" << endl;

return;

// If the node to delete is the head

if (head->data == value) {

Node* temp = head;

head = head->next;

delete temp;

return;

// Traverse the list to find the node to delete

Node* temp = head;

while (temp->next != nullptr && temp->next->data != value) {

temp = temp->next;

// If the value is not found

if (temp->next == nullptr) {

cout << "Value not found!" << endl;

} else {

// Delete the node

Node* nodeToDelete = temp->next;

temp->next = temp->next->next;
delete nodeToDelete;

// Function to display the list

void display() {

if (head == nullptr) {

cout << "List is empty!" << endl;

return;

Node* temp = head;

while (temp != nullptr) {

cout << temp->data << " -> ";

temp = temp->next;

cout << "nullptr" << endl;

// Destructor to free memory

~SinglyLinkedList() {

Node* current = head;

Node* nextNode;

while (current != nullptr) {

nextNode = current->next;

delete current;

current = nextNode;

};

int main() {

SinglyLinkedList list;

// Insert elements at the end

list.insertEnd(10);

list.insertEnd(20);
list.insertEnd(30);

list.insertEnd(40);

cout << "List after inserting elements at the end: ";

list.display();

// Insert element at the beginning

list.insertBegin(5);

cout << "List after inserting 5 at the beginning: ";

list.display();

// Delete an element

list.deleteNode(20);

cout << "List after deleting 20: ";

list.display();

// Try deleting a non-existing element

list.deleteNode(100);

return 0;

}
5. Implementation of Stack operations using array or linked list.

Array list

#include <stdio.h>

#include <stdlib.h>

#define MAX 5

int stack[MAX], top = -1, i; // Declare 'i' globally

void push(int value) {

if (top == MAX - 1)

printf("Stack Overflow!\n");

else

stack[++top] = value;

void pop() {

if (top == -1)

printf("Stack Underflow!\n");

else

printf("Popped: %d\n", stack[top--]);

void display() {

if (top == -1)

printf("Stack is empty.\n");

else {

printf("Stack: ");

for (i = top; i >= 0; i--) // Use the global variable 'i'

printf("%d ", stack[i]);

printf("\n");

int main() {

int choice, value;

do {

printf("\n1. Push 2. Pop 3. Display 4. Exit\nChoice: ");

scanf("%d", &choice);
if (choice == 1) {

printf("Enter value: ");

scanf("%d", &value);

push(value);

} else if (choice == 2)

pop();

else if (choice == 3)

display();

} while (choice != 4);

printf("Exiting...\n");

return 0;

}
Linked List

#include <iostream>

using namespace std;

// Node structure

struct Node {

int data;

Node* next;

};

// Stack class using linked list

class StackLinkedList {

private:

Node* top;

public:

// Constructor to initialize stack

StackLinkedList() {

top = nullptr;

// Push operation

void push(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = top;

top = newNode;

// Pop operation

int pop() {

if (top == nullptr) {

cout << "Stack Underflow!" << endl;

return -1;

Node* temp = top;

top = top->next;

int poppedValue = temp->data;


delete temp;

return poppedValue;

// Peek operation

int peek() {

if (top == nullptr) {

cout << "Stack is empty!" << endl;

return -1;

return top->data;

// Check if stack is empty

bool isEmpty() {

return top == nullptr;

// Display stack contents

void display() {

if (top == nullptr) {

cout << "Stack is empty!" << endl;

return;

Node* temp = top;

cout << "Stack contents: ";

while (temp != nullptr) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

// Destructor to free memory

~StackLinkedList() {

while (top != nullptr) {


Node* temp = top;

top = top->next;

delete temp;

};

int main() {

StackLinkedList stack;

stack.push(10);

stack.push(20);

stack.push(30);

stack.push(40);

stack.display();

cout << "Peek: " << stack.peek() << endl;

cout << "Pop: " << stack.pop() << endl;

stack.display();

stack.push(50);

stack.display();

return 0;

}
6. Implementation of Stack Applications.
a. Postfix Evaluation

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <math.h>

#define MAX 100

// Stack structure and utility functions

typedef struct {

int data[MAX];

int top;

} Stack;

void push(Stack* s, int value) {

if (s->top == MAX - 1) {

printf("Stack Overflow\n");

exit(EXIT_FAILURE);

s->data[++(s->top)] = value;

int pop(Stack* s) {

if (s->top == -1) {

printf("Stack Underflow\n");

exit(EXIT_FAILURE);

return s->data[(s->top)--];

// Evaluate postfix expression

int evaluatePostfix(char* expr) {

Stack s;

s.top = -1; // Initialize stack explicitly

int i = 0, op1, op2;

while (expr[i] != '\0') {

if (isdigit(expr[i])) {
push(&s, expr[i] - '0');

} else {

op2 = pop(&s);

op1 = pop(&s);

switch (expr[i]) {

case '+': push(&s, op1 + op2); break;

case '-': push(&s, op1 - op2); break;

case '*': push(&s, op1 * op2); break;

case '/':

if (op2 == 0) {

printf("Division by zero error\n");

exit(EXIT_FAILURE);

push(&s, op1 / op2);

break;

case '^': push(&s, pow(op1, op2)); break;

default:

printf("Invalid operator '%c'\n", expr[i]);

exit(EXIT_FAILURE);

i++;

return pop(&s);

int main() {

char expr[MAX];

printf("Enter postfix expression: ");

scanf("%s", expr);

printf("Result: %d\n",
evaluatePostfix(expr));

return 0;

}
7. Implementation of Linear Queue operations using array or linked list

Arraylist

#include <iostream>

using namespace std;

class Queue {

private:

int* arr;

int front;

int rear;

int capacity;

public:

// Constructor to initialize the queue

Queue(int size) {

capacity = size;

arr = new int[capacity];

front = -1;

rear = -1;

// Destructor to free memory

~Queue() {

delete[] arr;

// Check if the queue is empty

bool isEmpty() {

return front == -1;

// Check if the queue is full

bool isFull() {

return rear == capacity - 1;

// Add an element to the rear of the queue

void enqueue(int value) {

if (isFull()) {
cout << "Queue is full!" << endl;

return;

if (front == -1) {

front = 0; // First element enqueued

arr[++rear] = value;

// Remove an element from the front of the queue

void dequeue() {

if (isEmpty()) {

cout << "Queue is empty!" << endl;

return;

if (front == rear) {

front = rear = -1; // Queue becomes empty

} else {

front++;

// Get the element at the front of the queue

int getFront() {

if (isEmpty()) {

cout << "Queue is empty!" << endl;

return -1;

return arr[front];

// Get the size of the queue

int size() {

if (isEmpty()) {

return 0;

}
return rear - front + 1;

};

int main() {

Queue q(5);

q.enqueue(1);

q.enqueue(20);

q.enqueue(30);

cout << "Front element: " << q.getFront() << endl;

q.dequeue();

cout << "Front element after dequeue: " << q.getFront() << endl;

cout << "Queue size: " << q.size() << endl;

return 0;

}
LinkedList

#include <iostream>

using namespace std;

// Node structure to represent each element in the queue

struct Node {

int data;

Node* next;

};

class Queue {

private:

Node* front;

Node* rear;

public:

// Constructor to initialize the queue

Queue() {

front = rear = nullptr;

// Check if the queue is empty

bool isEmpty() {

return front == nullptr;

// Add an element to the rear of the queue

void enqueue(int value) {

Node* newNode = new Node;

newNode->data = value;

newNode->next = nullptr;

if (isEmpty()) {

front = rear = newNode;

} else {

rear->next = newNode;

rear = newNode;

}
// Remove an element from the front of the queue

void dequeue() {

if (isEmpty()) {

cout << "Queue is empty!" << endl;

return;

Node* temp = front;

front = front->next;

delete temp;

if (front == nullptr) {

rear = nullptr; // Queue becomes empty

// Get the element at the front of the queue

int getFront() {

if (isEmpty()) {

cout << "Queue is empty!" << endl;

return -1;

return front->data;

// Get the size of the queue

int size() {

int count = 0;

Node* temp = front;

while (temp != nullptr) {

count++;

temp = temp->next;

return count;

};

int main() {
Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

cout << "Front element: " << q.getFront() << endl;

q.dequeue();

cout << "Front element after dequeue: " << q.getFront() << endl;

cout << "Queue size: " << q.size() << endl;

return 0;

}
8. Implementation of BST and its traversal techniques
a. Inorder

#include <iostream>

using namespace std;

// Structure of the node

struct Node {

int data;

Node* left;

Node* right;

// Constructor to initialize a node

Node(int value) {

data = value;

left = nullptr;

right = nullptr;

};

// Function to insert a node in the BST

Node* insert(Node* root, int value) {

if (root == nullptr) {

// If the tree is empty, create a new node

return new Node(value);

if (value < root->data) {

// If the value is smaller, insert in the left subtree

root->left = insert(root->left, value);

} else {

// If the value is larger, insert in the right subtree

root->right = insert(root->right, value);

return root;

// Inorder Traversal of the BST (Left, Root, Right)

void inorderTraversal(Node* root) {


if (root == nullptr) {

return; // Base case: if the node is null, return

inorderTraversal(root->left); // Visit left subtree

cout << root->data << " "; // Visit root (current node)

inorderTraversal(root->right); // Visit right subtree

int main() {

Node* root = nullptr;

// Insert nodes into the BST

root = insert(root, 50);

root = insert(root, 30);

root = insert(root, 20);

root = insert(root, 40);

root = insert(root, 70);

root = insert(root, 60);

root = insert(root, 80);

// Perform Inorder Traversal

cout << "Inorder Traversal of the BST: ";

inorderTraversal(root); // Output: 20 30 40 50 60 70 80

cout << endl;

return 0;

}
b. Preorder

#include <iostream>

using namespace std;

// Structure of the node

struct Node {

int data;

Node* left;

Node* right;

// Constructor to initialize a node

Node(int value) {

data = value;

left = nullptr;

right = nullptr;

};

// Function to insert a node in the BST

Node* insert(Node* root, int value) {

if (root == nullptr) {

// If the tree is empty, create a new node

return new Node(value);

if (value < root->data) {

// If the value is smaller, insert in the left subtree

root->left = insert(root->left, value);

} else {

// If the value is larger, insert in the right subtree

root->right = insert(root->right, value);

return root;

// Preorder Traversal of the BST (Root, Left, Right)

void preorderTraversal(Node* root) {

if (root == nullptr) {
return; // Base case: if the node is null, return

cout << root->data << " "; // Visit root (current node)

preorderTraversal(root->left); // Visit left subtree

preorderTraversal(root->right); // Visit right subtree

int main() {

Node* root = nullptr;

// Insert nodes into the BST

root = insert(root, 50);

root = insert(root, 30);

root = insert(root, 20);

root = insert(root, 40);

root = insert(root, 70);

root = insert(root, 60);

root = insert(root, 80);

// Perform Preorder Traversal

cout << "Preorder Traversal of the BST: ";

preorderTraversal(root); // Output: 50 30 20 40 70 60 80

cout << endl;

return 0;

}
c. PostOrder

#include <iostream>

using namespace std;

// Structure of the node

struct Node {

int data;

Node* left;

Node* right;

// Constructor to initialize a node

Node(int value) {

data = value;

left = nullptr;

right = nullptr;

};

// Function to insert a node in the BST

Node* insert(Node* root, int value) {

if (root == nullptr) {

// If the tree is empty, create a new node

return new Node(value);

if (value < root->data) {

// If the value is smaller, insert in the left subtree

root->left = insert(root->left, value);

} else {

// If the value is larger, insert in the right subtree

root->right = insert(root->right, value);

return root;

// Postorder Traversal of the BST (Left, Right, Root)

void postorderTraversal(Node* root) {

if (root == nullptr) {
return; // Base case: if the node is null, return

postorderTraversal(root->left); // Visit left subtree

postorderTraversal(root->right); // Visit right subtree

cout << root->data << " "; // Visit root (current node)

int main() {

Node* root = nullptr;

// Insert nodes into the BST

root = insert(root, 50);

root = insert(root, 30);

root = insert(root, 20);

root = insert(root, 40);

root = insert(root, 70);

root = insert(root, 60);

root = insert(root, 80);

// Perform Postorder Traversal

cout << "Postorder Traversal of the BST: ";

postorderTraversal(root); // Output: 20 40 30 60 80 70 50

cout << endl;

return 0;

}
9. Implementation of Graph Traversal Technique.
a. Depth First Search

#include <iostream>

#include <vector>

using namespace std;

// Class representing a graph using an adjacency list

class Graph {

public:

int vertices; // Number of vertices

vector<vector<int>> adjList; // Adjacency list

// Constructor

Graph(int vertices) {

this->vertices = vertices;

adjList.resize(vertices);

// Function to add an edge to the graph

void addEdge(int u, int v) {

adjList[u].push_back(v); // Add v to the adjacency list of u

adjList[v].push_back(u); // Since the graph is undirected, add u to v's list as well

// Function to perform Depth First Search (DFS) starting from a given vertex

void dfs(int vertex, vector<bool>& visited) {

visited[vertex] = true; // Mark the current node as visited

cout << vertex << " "; // Process the current node (print it)

// Recur for all the vertices adjacent to this vertex

for (int neighbor : adjList[vertex]) {

if (!visited[neighbor]) { // If the neighbor hasn't been visited

dfs(neighbor, visited); // Recur for the neighbor

// Function to call DFS for all unvisited nodes (for disconnected graphs)

void dfsTraversal() {
vector<bool> visited(vertices, false); // Initialize visited array with false

// Call dfs for each vertex (in case of disconnected graph)

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

if (!visited[i]) {

dfs(i, visited); // Call DFS for each unvisited vertex

};

int main() {

// Create a graph with 6 vertices

Graph g(6);

// Add edges to the graph

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 3);

g.addEdge(1, 4);

g.addEdge(2, 5);

cout << "Depth First Search (DFS) Traversal of the graph: ";

// Perform DFS traversal starting from vertex 0

g.dfsTraversal();

return 0;

}
b. Breadth First Search

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

// Class representing a graph using an adjacency list

class Graph {

public:

int vertices; // Number of vertices

vector<vector<int>> adjList; // Adjacency list

// Constructor

Graph(int vertices) {

this->vertices = vertices;

adjList.resize(vertices);

// Function to add an edge to the graph

void addEdge(int u, int v) {

adjList[u].push_back(v); // Add v to the adjacency list of u

adjList[v].push_back(u); // Since the graph is undirected, add u to v's list as well

// Function to perform Breadth First Search (BFS) starting from a given vertex

void bfs(int startVertex) {

vector<bool> visited(vertices, false); // Visited array to keep track of visited nodes

queue<int> q; // Queue to manage the BFS process

// Mark the start vertex as visited and enqueue it

visited[startVertex] = true;

q.push(startVertex);

while (!q.empty()) {

int vertex = q.front();

q.pop(); // Remove the front element from the queue

cout << vertex << " "; // Process the current node (print it)

// Visit all adjacent vertices of the current node

for (int neighbor : adjList[vertex]) {


if (!visited[neighbor]) {

visited[neighbor] = true; // Mark the neighbor as visited

q.push(neighbor); // Enqueue the unvisited neighbor

// Function to call BFS for all unvisited nodes (for disconnected graphs)

void bfsTraversal() {

vector<bool> visited(vertices, false); // Initialize visited array with false

// Call bfs for each vertex (in case of disconnected graph)

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

if (!visited[i]) {

bfs(i); // Call BFS for each unvisited vertex

};

int main() {

// Create a graph with 6 vertices

Graph g(6);

// Add edges to the graph

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 3);

g.addEdge(1, 4);

g.addEdge(2, 5);

cout << "Breadth First Search (BFS) Traversal of the graph: ";

// Perform BFS traversal starting from vertex 0

g.bfsTraversal();

return 0;

}
10. Create a Minimum Spanning Tree using Kruskal’s Algorithm.

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Structure to represent an edge

struct Edge {

int u, v, weight;

// Constructor to initialize an edge

Edge(int u, int v, int weight) {

this->u = u;

this->v = v;

this->weight = weight;

};

// Disjoint Set Union (DSU) or Union-Find class

class DisjointSet {

public:

vector<int> parent, rank;

// Constructor to initialize the DSU

DisjointSet(int n) {

parent.resize(n);

rank.resize(n, 0);

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

parent[i] = i; // Initially, each node is its own parent

// Find function with path compression

int find(int u) {

if (parent[u] != u) {

parent[u] = find(parent[u]); // Path compression

return parent[u];
}

// Union function by rank

void unionSets(int u, int v) {

int root_u = find(u);

int root_v = find(v);

if (root_u != root_v) {

// Union by rank to keep the tree flat

if (rank[root_u] > rank[root_v]) {

parent[root_v] = root_u;

} else if (rank[root_u] < rank[root_v]) {

parent[root_u] = root_v;

} else {

parent[root_v] = root_u;

rank[root_u]++;

};

// Kruskal's Algorithm to find the Minimum Spanning Tree

void kruskal(int n, vector<Edge>& edges) {

// Sort the edges in non-decreasing order of their weight

sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {

return a.weight < b.weight;

});

DisjointSet dsu(n); // Initialize DSU for `n` vertices

vector<Edge> mst; // To store the edges of the MST

// Process each edge

for (const Edge& e : edges) {

// If including this edge does not form a cycle, add it to the MST

if (dsu.find(e.u) != dsu.find(e.v)) {

dsu.unionSets(e.u, e.v);

mst.push_back(e);

}
}

// Output the MST edges

cout << "Edges in the Minimum Spanning Tree (MST):\n";

int totalWeight = 0;

for (const Edge& e : mst) {

cout << e.u << " -- " << e.v << " == " << e.weight << "\n";

totalWeight += e.weight;

cout << "Total weight of MST: " << totalWeight << endl;

int main() {

// Number of vertices and edges

int n = 6; // Number of vertices

vector<Edge> edges;

// Add edges to the graph (u, v, weight)

edges.push_back(Edge(0, 1, 4));

edges.push_back(Edge(0, 2, 3));

edges.push_back(Edge(1, 2, 1));

edges.push_back(Edge(1, 3, 2));

edges.push_back(Edge(2, 3, 4));

edges.push_back(Edge(3, 4, 2));

edges.push_back(Edge(4, 5, 6));

edges.push_back(Edge(2, 5, 5));

// Run Kruskal's algorithm

kruskal(n, edges);

return 0;

You might also like