0% found this document useful (0 votes)
25 views

Queue Implementation (1)

Uploaded by

s14anj
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)
25 views

Queue Implementation (1)

Uploaded by

s14anj
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/ 32

Queue Implementation:

package DataStructure;

public class NormalQueue {


int front;
int rear;
int count;
Object[] arr;
int size;

// Constructor to initialize the queue


NormalQueue(int size) {
this.size = size;
front = 0;
rear = -1; // Initialize rear to -1 so that first enqueue correctly sets it to 0
count = 0;
arr = new Object[size];
}

// Enqueue: Adds an element to the rear of the queue


public void enqueue(Object ele) {
if (isFull()) {
System.out.println("Queue is full");
return;
}

// Increment rear and wrap around using modulo


rear = (rear + 1) % size;
arr[rear] = ele;
count++;
}

// Dequeue: Removes an element from the front of the queue


public Object dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
}

Object item = arr[front];


front = (front + 1) % size;
count--;
return item;
}

// Check if the queue is full


public boolean isFull() {
return count == size;
}

// Check if the queue is empty


public boolean isEmpty() {
return count == 0;
}

// Display the contents of the queue


public void display() {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}

System.out.println("Queue elements:");
for (int i = 0; i < count; i++) {
System.out.println(arr[(front + i) % size]);
}
}

// Main method to test the queue


public static void main(String[] args) {
NormalQueue q = new NormalQueue(5);

// Enqueue elements
q.enqueue(8);
q.enqueue(6);
q.enqueue(3);
q.enqueue(2);
q.enqueue(1);

// Display the queue


System.out.println("After enqueue:");
q.display();

// Dequeue an element
System.out.println("Dequeued element: " + q.dequeue());

// Display the queue after dequeue


System.out.println("After dequeue:");
q.display();
}
}

Circular Queue Implemenation


package DataStructure;

public class CircularQueue {


private int front;
private int rear;
private int count;
private int size;
private Object[] arr;

// Constructor to initialize the circular queue


public CircularQueue(int size) {
this.size = size;
front = 0;
rear = -1; // Rear starts before the front
count = 0; // Count of elements in the queue
arr = new Object[size];
}

// Method to add an element to the rear of the queue (normal enqueue)


public void enqueue(Object ele) {
if (isFull()) {
System.out.println("Queue is full");
return;
}

rear = (rear + 1) % size;


arr[rear] = ele;
count++;
}

// Method to remove an element from the front of the queue (normal dequeue)
public Object dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
}

Object item = arr[front];


front = (front + 1) % size;
count--;
return item;
}

// Method to check if the queue is full


public boolean isFull() {
return count == size;
}

// Method to check if the queue is empty


public boolean isEmpty() {
return count == 0;
}

// Method to peek at the front element of the queue


public Object peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
}
return arr[front];
}

// Method to get the current size of the queue


public int getSize() {
return count;
}

// Method to clear the queue


public void clear() {
front = 0;
rear = -1;
count = 0;
arr = new Object[size];
}

// Method to display all elements in the queue


public void display() {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}

System.out.print("Queue elements: ");


for (int i = 0; i < count; i++) {
System.out.print(arr[(front + i) % size] + " ");
}
System.out.println();
}
// Method to add an element at a specific index in the queue
public void addAtIndex(int index, Object ele) {
if (isFull()) {
System.out.println("Queue is full");
return;
}

if (index < 0 || index > count) {


System.out.println("Invalid index");
return;
}

// Shift elements to make space at the given index


int actualIndex = (front + index) % size;
int currentPos = (rear + 1) % size;
for (int i = count; i > index; i--) {
arr[(front + i) % size] = arr[(front + i - 1) % size];
}

// Insert the new element at the specified index


arr[actualIndex] = ele;
rear = (rear + 1) % size;
count++;
}

// Method to delete an element at a specific index in the queue


public void deleteAtIndex(int index) {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}

if (index < 0 || index >= count) {


System.out.println("Invalid index");
return;
}

// Shift elements to fill the gap at the given index


for (int i = index; i < count - 1; i++) {
arr[(front + i) % size] = arr[(front + i + 1) % size];
}

// Update rear and decrease the count


rear = (rear - 1 + size) % size;
count--;
}

// Main method to test the queue


public static void main(String[] args) {
CircularQueue q = new CircularQueue(5);

// Enqueue elements
q.enqueue(8);
q.enqueue(6);
q.enqueue(3);
q.enqueue(2);
q.enqueue(1);

System.out.println("Initial Queue:");
q.display();

// Dequeue an element
System.out.println("Dequeued element: " + q.dequeue());

// Display the queue after dequeue


System.out.println("After dequeue:");
q.display();

// Add element at specific index


System.out.println("Adding 4 at index 2");
q.addAtIndex(2, 4);
q.display();

// Delete element at specific index


System.out.println("Deleting element at index 1");
q.deleteAtIndex(1);
q.display();
}
}

Stack implementation:
package DataStructure;

public class CustomStack {


private int top;
private int size;
private Object[] arr;

// Constructor to initialize the stack


public CustomStack(int size) {
this.size = size;
top = -1; // Start with top at -1 to indicate an empty stack
arr = new Object[size];
}

// Push method to add an element to the stack


public void push(Object ele) {
if (isFull()) {
System.out.println("Stack is full");
return;
}
arr[++top] = ele;
}

// Pop method to remove and return the top element from the stack
public Object pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return null;
}
return arr[top--];
}

// Peek method to return the top element without removing it


public Object peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
return null;
}
return arr[top];
}

// Method to check if the stack is full


public boolean isFull() {
return top == size - 1;
}

// Method to check if the stack is empty


public boolean isEmpty() {
return top == -1;
}

// Method to get the current size of the stack


public int getSize() {
return top + 1;
}

// Method to clear the stack


public void clear() {
top = -1;
}

// Method to display all elements in the stack


public void display() {
if (isEmpty()) {
System.out.println("Stack is empty");
return;
}
System.out.print("Stack elements: ");
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

// Method to insert an element at a specific index in the stack


public void insertAtIndex(int index, Object ele) {
if (isFull()) {
System.out.println("Stack is full");
return;
}

if (index < 0 || index > top + 1) {


System.out.println("Invalid index");
return;
}

// Shift elements upwards to make space at the given index


for (int i = top; i >= index; i--) {
arr[i + 1] = arr[i];
}

// Insert the new element at the specified index


arr[index] = ele;
top++;
}

// Method to delete an element at a specific index in the stack


public void deleteAtIndex(int index) {
if (isEmpty()) {
System.out.println("Stack is empty");
return;
}

if (index < 0 || index > top) {


System.out.println("Invalid index");
return;
}

// Shift elements downwards to fill the gap at the specified index


for (int i = index; i < top; i++) {
arr[i] = arr[i + 1];
}

// Decrement the top pointer


top--;
}

// Main method to test the stack


public static void main(String[] args) {
CustomStack stack = new CustomStack(5);

// Push elements onto the stack


stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
System.out.println("Initial Stack:");
stack.display();

// Pop an element
System.out.println("Popped element: " + stack.pop());

// Display the stack after pop


System.out.println("After pop:");
stack.display();

// Insert an element at a specific index


System.out.println("Inserting 25 at index 1");
stack.insertAtIndex(1, 25);
stack.display();

// Delete an element at a specific index


System.out.println("Deleting element at index 2");
stack.deleteAtIndex(2);
stack.display();
}
}

Bubble Sort:
We have to check for the largest number and then we have to swap the in the same
array
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}

Selection Sort
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// Swap arr[i] and arr[minIdx]
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
}
}

Insertion Sort:
public class InsertionSort {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}

Merge Sort
public class MergeSort {
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

private static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];

for (int i = 0; i < n1; i++) L[i] = arr[left + i];


for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];

int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}
}

Quick Sort
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

private static 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;
}
}

Linear Search:
public class LinearSearch {
public static int linearSearch(int[] arr, int target) {
// Traverse through each element in the array
for (int i = 0; i < arr.length; i++) {
// If the target element is found, return its index
if (arr[i] == target) {
return i;
}
}
// Return -1 if the target element is not found
return -1;
}

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
int target = 30;
System.out.println("Array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();

int result = linearSearch(arr, target);

if (result != -1) {
System.out.println("Element " + target + " found at index " + result + ".");
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
}
Binary Search:
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;

while (left <= right) {


// Calculate the middle index
int mid = left + (right - left) / 2;

// Check if the target is at mid


if (arr[mid] == target) {
return mid;
}

// If target is greater, ignore the left half


if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
}
}

// Return -1 if the target is not found


return -1;
}

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
int target = 30;

System.out.println("Array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();

int result = binarySearch(arr, target);

if (result != -1) {
System.out.println("Element " + target + " found at index " + result + ".");
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
}
Binary Search Using recursion:
public class RecursiveBinarySearch {
public static int binarySearch(int[] arr, int left, int right, int target) {
// Base case: If the left index exceeds the right index, the element is not found
if (left > right) {
return -1;
}

// Calculate the middle index


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

// Check if the target is at mid


if (arr[mid] == target) {
return mid;
}

// If the target is smaller, search in the left half


if (arr[mid] > target) {
return binarySearch(arr, left, mid - 1, target);
}

// If the target is larger, search in the right half


return binarySearch(arr, mid + 1, right, target);
}

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
int target = 30;
System.out.println("Array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();

// Call the recursive binary search function


int result = binarySearch(arr, 0, arr.length - 1, target);

if (result != -1) {
System.out.println("Element " + target + " found at index " + result + ".");
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
}
Accessing every element in array:
public class AccessMatrixElements {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

System.out.println("Matrix elements:");
for (int[] row : matrix) { // Loop through each row
for (int element : row) { // Loop through each element in the row
System.out.print(element + " ");
}
System.out.println(); // Move to the next row
}
}
}
Another approach:
public class AccessMatrixElements {
public static void main(String[] args) {
// Define a 2-D array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Access and print each element using nested loops


System.out.println("Matrix elements:");
for (int i = 0; i < matrix.length; i++) { // Loop through rows
for (int j = 0; j < matrix[i].length; j++) { // Loop through columns
System.out.print(matrix[i][j] + " "); // Access element at (i, j)
}
System.out.println(); // Move to the next row
}
}
}
BST
// Node class for the Binary Search Tree
class TreeNode {
int data;
TreeNode left, right;
// Constructor
TreeNode(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}

// Binary Search Tree class


class BinarySearchTree {
private TreeNode root;

// Insert a value into the BST


public void insert(int data) {
root = insertRec(root, data);
}

private TreeNode insertRec(TreeNode root, int data) {


if (root == null) {
return new TreeNode(data);
}
if (data < root.data) {
root.left = insertRec(root.left, data);
} else if (data > root.data) {
root.right = insertRec(root.right, data);
}
return root;
}
// Delete a value from the BST
public void delete(int data) {
root = deleteRec(root, data);
}

private TreeNode deleteRec(TreeNode root, int data) {


if (root == null) {
return null; // Base case: value not found
}

if (data < root.data) {


root.left = deleteRec(root.left, data); // Recur on the left subtree
} else if (data > root.data) {
root.right = deleteRec(root.right, data); // Recur on the right subtree
} else {
// Node to be deleted found
// Case 1: No child
if (root.left == null && root.right == null) {
return null;
}

// Case 2: One child


if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}

// Case 3: Two children


// Get in-order successor (smallest value in the right subtree)
root.data = minValue(root.right);

// Delete the in-order successor


root.right = deleteRec(root.right, root.data);
}
return root;
}

private int minValue(TreeNode root) {


int minValue = root.data;
while (root.left != null) {
root = root.left;
minValue = root.data;
}
return minValue;
}

// In-order Traversal (for testing)


public void inorderTraversal() {
inorderRec(root);
System.out.println();
}

private void inorderRec(TreeNode root) {


if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
}

// Main class to test the Binary Search Tree


public class Main {
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();

// Insert elements
bst.insert(50);
bst.insert(30);
bst.insert(70);
bst.insert(20);
bst.insert(40);
bst.insert(60);
bst.insert(80);

System.out.println("In-order Traversal before deletion:");


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

// Delete nodes
bst.delete(20); // Delete a leaf node
bst.delete(30); // Delete a node with one child
bst.delete(50); // Delete a node with two children

System.out.println("In-order Traversal after deletion:");


bst.inorderTraversal(); // Output: 40 60 70 80
}
}
DLL
// Node class for the doubly linked list
class Node {
int data;
Node next;
Node prev;

// Constructor
Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}

// Doubly Linked List class


class DoublyLinkedList {
private Node head;

// Constructor
public DoublyLinkedList() {
this.head = null;
}

// Add a node at a specific index


public void addAtIndex(int index, int data) {
Node newNode = new Node(data);

if (index == 0) { // Add at the head


if (head != null) {
newNode.next = head;
head.prev = newNode;
}
head = newNode;
return;
}

Node current = head;


int count = 0;

// Traverse the list to find the insertion point


while (current != null && count < index - 1) {
current = current.next;
count++;
}

if (current == null) {
System.out.println("Index out of bounds");
return;
}

// Insert the new node


newNode.next = current.next;
if (current.next != null) {
current.next.prev = newNode;
}
current.next = newNode;
newNode.prev = current;
}

// Print the list forward


public void printForward() {
Node current = head;
System.out.print("List: ");
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}

// Main class to test the DoublyLinkedList


public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();

// Add elements to the list


list.addAtIndex(0, 10); // Add at head
list.addAtIndex(1, 20); // Add at index 1
list.addAtIndex(2, 30); // Add at index 2
list.addAtIndex(1, 15); // Add at index 1
list.addAtIndex(0, 5); // Add at head

// Print the list


list.printForward(); // Output: List: 5 10 15 20 30
}
}
Binary Search Implemataion:
public class BinarySearchRecursive {
// Recursive method for binary search
public static int binarySearch(int[] arr, int low, int high, int target) {
if (low > high) {
return -1; // Base case: target not found
}

int mid = low + (high - low) / 2; // Avoids overflow compared to (low + high) / 2

if (arr[mid] == target) {
return mid; // Target found
}

if (target < arr[mid]) {


return binarySearch(arr, low, mid - 1, target); // Search in the left half
}

return binarySearch(arr, mid + 1, high, target); // Search in the right half


}

public static void main(String[] args) {


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

int result = binarySearch(arr, 0, arr.length - 1, target);

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

You might also like