0% found this document useful (0 votes)
11 views28 pages

LAB 1: Programming in C To Analyse The Complexity of Different Programs

The document discusses implementation of different data structures like stack, queue, circular queue, deque and priority queue using arrays and linked lists. It includes code snippets for insertion and deletion operations on these data structures and analyzing their time complexities.

Uploaded by

aayutiwari2003
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)
11 views28 pages

LAB 1: Programming in C To Analyse The Complexity of Different Programs

The document discusses implementation of different data structures like stack, queue, circular queue, deque and priority queue using arrays and linked lists. It includes code snippets for insertion and deletion operations on these data structures and analyzing their time complexities.

Uploaded by

aayutiwari2003
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/ 28

LAB 1: Programming in C to analyse the complexity of

different programs.

//Time complexity: O(1)


import java.io.*;

class timeComplexity {
public static void main(String[] args)
{
System.out.print("Hello World");
}
}

// Time complexity O(n)


class timeComplexity {

public static void main(String[] args)


{
int i, n = 8;
for (i = 1; i <= n; i++) {
System.out.printf("Hello World !!!\n");
}
}
}

// Time complexity O(log 2(n))


class timeComplexity {

public static void main(String[] args)


{
int i, n = 8;
for (i = 1; i <= n; i=i*2) {
System.out.println("Hello World !!!");
}
}
}
LAB 2: Implementation of Stack and Queue using array.

//Stack implementation using array.


class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX];

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}

int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}

int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}

void print(){
for(int i = top;i>-1;i--){
System.out.print(" "+ a[i]);
}
}
}
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
System.out.println("Top element is :" + s.peek());
System.out.print("Elements present in stack :");
s.print();
}
}

//Queue implementation using array


class Queue {
static private int front, rear, capacity;
static private int queue[];

Queue(int c)
{
front = rear = 0;
capacity = c;
queue = new int[capacity];
}

static void queueEnqueue(int data)


{

if (capacity == rear) {
System.out.printf("\nQueue is full\n");
return;
}
else {
queue[rear] = data;
rear++;
}
return;
}
static void queueDequeue()
{
if (front == rear) {
System.out.printf("\nQueue is empty\n");
return;
}
else {
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
return;
}
static void queueDisplay()
{
int i;
if (front == rear) {
System.out.printf("\nQueue is Empty\n");
return;
}
for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
}
return;
}
static void queueFront()
{
if (front == rear) {
System.out.printf("\nQueue is Empty\n");
return;
}
System.out.printf("\nFront Element is: %d",queue[front]);
return;
}
}

public class StaticQueueinjava {


public static void main(String[] args)
{
Queue q = new Queue(4);
q.queueDisplay();
q.queueEnqueue(20);
q.queueEnqueue(30);
q.queueEnqueue(40);
q.queueEnqueue(50);
q.queueDisplay();

q.queueEnqueue(60);
q.queueDisplay();

q.queueDequeue();
q.queueDequeue();
System.out.printf("\n\nafter two node deletion\n\n");
q.queueDisplay();

q.queueFront();
}
}
LAB 3: Implementation of stack and queue using Linked
list.

//Implementation of stack using linked list.


public class StackAsLinkedList {
StackNode root;
static class StackNode {
int data;
StackNode next;
StackNode(int data) { this.data = data; }
}

public boolean isEmpty()


{
if (root == null) {
return true;
}
else
return false;
}

public void push(int data)


{
StackNode newNode = new StackNode(data);

if (root == null) {
root = newNode;
}
else {
StackNode temp = root;
root = newNode;
newNode.next = temp;
}
System.out.println(data + " pushed to stack");
}

public int pop()


{
int popped = Integer.MIN_VALUE;
if (root == null) {
System.out.println("Stack is Empty");
}
else {
popped = root.data;
root = root.next;
}
return popped;
}
public int peek()
{
if (root == null) {
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
}
else {
return root.data;
}
}
public static void main(String[] args)
{

StackAsLinkedList sll = new StackAsLinkedList();

sll.push(10);
sll.push(20);
sll.push(30);

System.out.println(sll.pop() + " popped from stack");


System.out.println("Top element is " + sll.peek());
}
}

//Implementation of queue using linked list


class QNode {
int key;
QNode next;
public QNode(int key)
{
this.key = key;
this.next = null;
}
}
class Queue {
QNode front, rear;

public Queue() { this.front = this.rear = null; }


void enqueue(int key)
{
QNode temp = new QNode(key);
if (this.rear == null) {
this.front = this.rear = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
void dequeue()
{
if (this.front == null)
return;
QNode temp = this.front;
this.front = this.front.next;
if (this.front == null)
this.rear = null;
}
}
public class Test {
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
System.out.println("Queue Front : " + ((q.front != null) ?
(q.front).key : -1));
System.out.println("Queue Rear : " + ((q.rear != null) ?
(q.rear).key : -1));
}
}

LAB 4: Implementation of Circular queue, Dequeue and


priority queue array.
// Circular queue
import java.util.ArrayList;

class CircularQueue{
private int size, front, rear;
private ArrayList<Integer> queue = new ArrayList<Integer>();
CircularQueue(int size)
{
this.size = size;
this.front = this.rear = -1;
}
public void enQueue(int data)
{
if((front == 0 && rear == size - 1) ||
(rear == (front - 1) % (size - 1)))
{
System.out.print("Queue is Full");
}
else if(front == -1)
{
front = 0;
rear = 0;
queue.add(rear, data);
}

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


{
rear = 0;
queue.set(rear, data);
}

else
{
rear = (rear + 1);
if(front <= rear)
{
queue.add(rear, data);
}
else
{
queue.set(rear, data);
}
}
}
public int deQueue()
{
int temp;
if(front == -1)
{
System.out.print("Queue is Empty");
return -1;
}

temp = queue.get(front);
if(front == rear)
{
front = -1;
rear = -1;
}

else if(front == size - 1)


{
front = 0;
}
else
{
front = front + 1;
}
return temp;
}
public void displayQueue()
{
if(front == -1)
{
System.out.print("Queue is Empty");
return;
}
System.out.print("Elements in the " + "circular queue are: ");

if(rear >= front)


{
for(int i = front; i <= rear; i++)
{
System.out.print(queue.get(i));
System.out.print(" ");
}
System.out.println();
}
else
{
for(int i = front; i < size; i++)
{
System.out.print(queue.get(i));
System.out.print(" ");
}
for(int i = 0; i <= rear; i++)
{
System.out.print(queue.get(i));
System.out.print(" ");
}
System.out.println();
}
}
public static void main(String[] args)
{
CircularQueue q = new CircularQueue(5);
q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);

q.displayQueue();
int x = q.deQueue();
if(x != -1)
{
System.out.print("Deleted value = ");
System.out.println(x);
}

x = q.deQueue();
if(x != -1)
{
System.out.print("Deleted value = ");
System.out.println(x);
}

q.displayQueue();

q.enQueue(9);
q.enQueue(20);
q.enQueue(5);

q.displayQueue();

q.enQueue(20);
}
}

//Dequeue
class Deque {
static final int MAX = 100;
int arr[];
int front;
int rear;
int size;

public Deque(int size)


{
arr = new int[MAX];
front = -1;
rear = 0;
this.size = size;
}
boolean isFull()
{
return ((front == 0 && rear == size - 1)
|| front == rear + 1);
}
boolean isEmpty() { return (front == -1); }
void insertfront(int key)
{
if (isFull()) {
System.out.println("Overflow");
return;
}
if (front == -1) {
front = 0;
rear = 0;
}
else if (front == 0)
front = size - 1;

else
front = front - 1;
arr[front] = key;
}
void insertrear(int key)
{
if (isFull()) {
System.out.println(" Overflow ");
return;
}
if (front == -1) {
front = 0;
rear = 0;
}
else if (rear == size - 1)
rear = 0;
else
rear = rear + 1;
arr[rear] = key;
}
void deletefront()
{
if (isEmpty()) {
System.out.println("Queue Underflow\n");
return;
}
if (front == rear) {
front = -1;
rear = -1;
}
else
if (front == size - 1)
front = 0;

else
front = front + 1;
}
void deleterear()
{
if (isEmpty()) {
System.out.println(" Underflow");
return;
}
if (front == rear) {
front = -1;
rear = -1;
}
else if (rear == 0)
rear = size - 1;
else
rear = rear - 1;
}
int getFront()
{
if (isEmpty()) {
System.out.println(" Underflow");
return -1;
}
return arr[front];
}
int getRear()
{
if (isEmpty() || rear < 0) {
System.out.println(" Underflow\n");
return -1;
}
return arr[rear];
}
public static void main(String[] args)
{
Deque dq = new Deque(5);
System.out.println("Insert element at rear end : 5 ");
dq.insertrear(5);

System.out.println("insert element at rear end : 10 ");


dq.insertrear(10);

System.out.println("get rear element : "+ dq.getRear());


dq.deleterear();
System.out.println("After delete rear element new rear become :
"+ dq.getRear());

System.out.println("inserting element at front


end");dq.insertfront(15);
System.out.println("get front element: "+ dq.getFront());

dq.deletefront();
System.out.println("After delete front element new front become :
"+ +dq.getFront());
}
}

LAB 5: Implementation of Quick Sort, Merge Sort, Linear


Search and Binary Search.
//Quick Sort
class QuickSort
{
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1);
for (int j=low; j<high; j++)
{
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;

return i+1;
}
void sort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;

QuickSort ob = new QuickSort();


ob.sort(arr, 0, n-1);
System.out.println("sorted array");
printArray(arr);
}
}

//Merge Sort
import java.io.*;

class MergeSort {
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];

// Copy data to temp arrays


for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r)
{
if (l < r) {
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6, 7 };

System.out.println("Given array is");


printArray(arr);

MergeSort ob = new MergeSort();


ob.sort(arr, 0, arr.length - 1);

System.out.println("\nSorted array is");


printArray(arr);
}
}

//Linear Search
class LinearSearch {
static int search(int arr[], int n, int x)
{
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}

public static void main(String[] args)


{
int[] arr = { 3, 4, 1, 7, 5 };
int n = arr.length;
int x = 4;
int index = search(arr, n, x);
if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at position " + index);
}
}

// Binary Search
class BinarySearch {
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();

int arr[] = { 2, 3, 4, 10, 40 };


int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);

if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index "+ result);
}
}

LAB 6: Implementation of Binary Search Tree and various


traversal: Inorder, Postorder and Preorder.
import java.io.*;

class Node {
int data;
Node left;
Node right;
Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}

class bst {
public static void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
public static void main(String[] args)
{
Node root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
System.out.print("Inorder Traversal: ");
printInorder(root);
}
}

LAB 7: Implementation of algorithms based on Greedy


approach.

import java.io.*;
class greedy
{
static int count(int n)
{
if (n < 4)
return -1;
int rem = n % 4;
if (rem == 0)
return n / 4;
if (rem == 1) {
if (n < 9)
return -1;
return (n - 9) / 4 + 1;
}
if (rem == 2)
return (n - 6) / 4 + 1;
if (rem == 3)
{
if (n < 15)
return -1;
return (n - 15) / 4 + 2;
}
return 0;
}
public static void main (String[] args)
{
int n = 90;
System.out.println(count(n));

n = 143;
System.out.println(count(n));
}
}

LAB 8: Implementation of algorithm based on Dynamic


Programming.
import java.util.*;

class bionomialCoeficient {

static int binomialCoeff(int n, int k)


{
if (k > n)
return 0;
if (k == 0 || k == n)
return 1;
return binomialCoeff(n - 1, k - 1)
+ binomialCoeff(n - 1, k);
}
public static void main(String[] args)
{
int n = 5, k = 2;
System.out.printf("Value of C(%d, %d) is %d ", n, k,
binomialCoeff(n, k));
}
}

LAB 9: Implementation of graph traversal: BFS and DFS


import java.util.LinkedList;
import java.util.Queue;

class Graph {
int vertices;
LinkedList<Integer>[] adjList;
@SuppressWarnings("unchecked") Graph(int vertices)
{
this.vertices = vertices;
adjList = new LinkedList[vertices];
for (int i = 0; i < vertices; ++i)
adjList[i] = new LinkedList<>();
}
void addEdge(int u, int v) { adjList[u].add(v); }
void bfs(int startNode)
{
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[vertices];
visited[startNode] = true;
queue.add(startNode);
while (!queue.isEmpty()) {
int currentNode = queue.poll();
System.out.print(currentNode + " ");
for (int neighbor : adjList[currentNode]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}

public class Main {


public static void main(String[] args)
{
int vertices = 5;
Graph graph = new Graph(vertices);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 4);
System.out.print(
"Breadth First Traversal starting from vertex 0: ");
graph.bfs(0);
}
}

//DFS
import java.io.*;
import java.util.*;

class Graph {
private int V;
private LinkedList<Integer> adj[];
@SuppressWarnings("unchecked") Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w)
{
// Add w to v's list.
adj[v].add(w);
}
void DFSUtil(int v, boolean visited[])
{
visited[v] = true;
System.out.print(v + " ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
void DFS(int v)
{
boolean visited[] = new boolean[V];
DFSUtil(v, visited);
}
public static void main(String args[])
{
Graph g = new Graph(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);

System.out.println("Following is Depth First Traversal "+


"(starting from vertex 2)");

// Function call
g.DFS(2);
}
}
LAB 10: Implementation of MST algorithms in Graphs:
Prim and Kruskal.
import java.io.*;
import java.lang.*;
import java.util.*;

class MST {
private static final int V = 5;
int minKey(int key[], Boolean mstSet[])
{
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}

return min_index;
}
void printMST(int parent[], int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + "\t"+
graph[i][parent[i]]);
}
void primMST(int graph[][])
{
int parent[] = new int[V];
int key[] = new int[V]
Boolean mstSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] != 0 && mstSet[v] == false
&& graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
printMST(parent, graph);
}

public static void main(String[] args)


{
MST t = new MST();
int graph[][] = new int[][] { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
t.primMST(graph);
}
}

LAB 11: Implementation of shortest path algorithm in


graphs.
import java.io.*;
import java.lang.*;
import java.util.*;

class ShortestPath {
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}

return min_index;
}
void printSolution(int dist[])
{
System.out.println(
"Vertex \t\t Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " \t\t " + dist[i]);
}
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V];
Boolean sptSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] != 0
&& dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist);
}
public static void main(String[] args)
{
int graph[][]= new int[][] { { 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 } };
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}

You might also like