0% found this document useful (0 votes)
6 views40 pages

Explanation of BCA Programs

The document outlines various data structures and algorithms in programming, including arrays, stacks, queues, linked lists, and tree traversal methods. It explains their implementations in Java with real-world scenarios and highlights their importance in computer science. Key concepts such as binary search, sorting algorithms, and the differences between normal and circular queues are also discussed.

Uploaded by

anujkhatkar100
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)
6 views40 pages

Explanation of BCA Programs

The document outlines various data structures and algorithms in programming, including arrays, stacks, queues, linked lists, and tree traversal methods. It explains their implementations in Java with real-world scenarios and highlights their importance in computer science. Key concepts such as binary search, sorting algorithms, and the differences between normal and circular queues are also discussed.

Uploaded by

anujkhatkar100
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/ 40

1- Yeh program ek simple array create karta hai aur uske elements ko print karta hai.

2- Yeh program ek element ko array me search karta hai.


3- Yeh sorted array me binary search algorithm lagata hai.
4- Stack ek LIFO data structure hai — Last In First Out.
5- Queue ek FIFO data structure hai — First In First Out.
6- Linked List me nodes hoti hain jo ek doosre se linked hoti hain.
7- Circular Queue — Queue ka circular version hai jisme last ke baad fir first position pe
aate hain.
8- Doubly Linked List me har node ke pass do pointer hote hain — ek next aur ek previous.

9-Tree traversal ek tree ke sabhi nodes ko visit karne ka method hai:

Inorder: Left → Root → Right

Preorder: Root → Left → Right

Postorder: Left → Right → Root

10-Binary Search Tree me left side chhote aur right side bade values hote hain. Yeh program
insertion aur searching dono karta hai.

11- Graph ko represent karne ka yeh matrix method hai jisme 1 edge dikhata hai aur 0 no
connection dikhata hai.

12- HashMap key-value pair ko store karta hai aur fast lookup provide karta hai. Yeh hashing ka
basic example hai.

13-Bubble Sort adjacent elements ko compare karta hai aur swap karta hai jab tak pura array
sorted na ho jaye.

14- Selection Sort me har baar minimum element ko select karke uski correct position pe swap
kiya jata hai.

Program1 –

public class ArrayExample {

This is the declaration of a class named ArrayExample.

In Java, everything runs inside a class.


Think of it like creating a blueprint for a house — this is your blueprint.

public static void main(String[] args) {

public means this method is accessible from anywhere.

static means it belongs to the class and not objects.

void means this method won’t return any value.

main() is the program’s entry point — like a switch to start your code.

String[] args allows command-line arguments.

In real life, this is like pressing the Start Button on a machine.

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

 Here you're creating an integer array with 5 elements. Loop through each element from
index 0 to 4.

Arrays are like boxes arranged in a row, and each has a number inside.

�Change Suggestion:

If you want a dynamic array:

int[] arr = new int[5];

arr[0] = 10;

arr[1] = 20; // etc.

for(int i = 0; i < arr.length; i++) {

A for loop is used to iterate through the array.

i = 0 means starting from the first element.

i < arr.length ensures the loop stops at the last element.

This is like checking each shelf in a rack, one by one.

System.out.println("Element at index " + i + ": " + arr[i]);

This prints the current element with its index.


For example: Element at index 0: 10

�Real-World Use:

Used for storing student marks, product prices, or sensor readings.

Arrays are good when you know the number of elements in advance.

�Real-Life Change Example:

If you wanted to store names instead of numbers:

String[] names = {"Alice", "Bob", "Charlie"};

for(int i = 0; i < names.length; i++) {

System.out.println("Student " + i + ": " + names[i]);

This will output:

Student 0: Alice

Student 1: Bob

Student 2: Charlie

� Real-world scenario: Class attendance, employee names, Storing marks, prices, sensor
data.etc.

Program2–
Real-World Scenario:
1�⃣ Grocery Store Barcode Search:

 You have a list of product barcodes.


 The cashier scans for a barcode.
If the product matches one in the list → print location.
If not → "Product not found."
2�⃣ Library Book Search:

 Searching a book’s accession number manually through the records.


 This is how libraries worked before digital systems.

Limitations of Linear Search:


 Slow for large data.
 Searches one by one, even if the list has millions of items.
 Use it when:
o Data is unsorted.
o Small-sized datasets.

Why Important?
 Foundation of search logic.
 Easy to understand and apply.
 Forms the base for more advanced searches like Binary Search or Hash-based Search.

Program3-
import java.util.Arrays;

 This line imports Java's Arrays utility.


 It allows you to use useful functions like binarySearch().
 Like bringing a calculator into your exam — saves manual work.

�public class BinarySearchExample {

 Defines a class to hold your main logic.

�public static void main(String[] args) {

 The entry point of the program, where Java starts executing.

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

 Creates a sorted array.


 Important: Binary Search only works on sorted data.

�int search = 30;

 This is the number you want to find.


 Imagine you’re searching for Product ID = 30 in an organized warehouse shelf.

�int result = Arrays.binarySearch(arr, search);

 Java’s built-in function performs binary search.


 How it works:
o Checks the middle element.
o If it matches — return the index.
o If search < middle, it searches the left half.
o If search > middle, it searches the right half.
 Repeats until it finds the number or concludes it's not present.

�if (result >= 0) {

 If result is >= 0, the item is found.


 result holds the index of the item.

�System.out.println(search + " found at index " + result);

 Prints where the item was found.

�else { System.out.println(search + " not found."); }

 If result is negative, the number is not in the list.

� Real-World Scenario
1�⃣ Phone Book Lookup

 Names are alphabetically sorted.


 If you're searching for "Sanjay" in a phone book:
o You open the middle page.
o If "Sanjay" is earlier alphabetically — flip to the first half.
o If "Sanjay" is later — flip to the second half.

2�⃣ Online Shopping (Product ID Search)

 Product databases are indexed.


 When you search for a product by ID, a binary-like algorithm runs for fast lookup.

Why Is It Important?
 Faster than linear search for large datasets.
 Used in databases, search engines, and operating systems.
 Learning it helps you think like a problem-solver.

Program 4: Stack Implementation Using Array in Java


int[] stack = new int[5];

 Creates an array of size 5.


 This is your stack storage.
 Think of it like a stack of plates!

�int top = -1;

 top tracks the current position.


 -1 means the stack is empty.
 After each push, top increases; after each pop, it decreases.

�void push(int data)

 Adds a new element to the top of the stack.

java
CopyEdit
if (top == stack.length - 1) {
 Checks if the stack is already full.
 No more room if top is at the last index.

java
CopyEdit
stack[++top] = data;

 First, top is incremented (++top).


 Then the data is stored at that position.

�void pop()

 Removes the top element from the stack.

java
CopyEdit
if (top == -1) {

 If top == -1, the stack is empty (underflow condition).

java
CopyEdit
System.out.println(stack[top] + " popped from stack");
top--;

 Prints and decreases top by 1, effectively removing the top item.

�void display()

 Shows all current elements in the stack.


 If top == -1, the stack is empty.
 Otherwise, it prints from index 0 to top.

�public static void main(String[] args)

 Main function to run the program.

java
CopyEdit
s.push(10);
s.push(20);
s.push(30);

 Pushes three values onto the stack.

java
CopyEdit
s.display();

 Shows the current state of the stack.

java
CopyEdit
s.pop();

 Removes the last added item.

java
CopyEdit
s.display();

 Shows the new state after popping.

� Real-World Scenario
1�⃣ Undo Feature in Word Processors:

 Every action (typing, deleting) is pushed onto the stack.


 When you press Ctrl + Z, the last action is popped.

2�⃣ Browser Back Button:

 Each visited page URL is pushed onto a stack.


 When you press "Back," the last URL is popped and loaded.

Why Important?
 Stack is used in:
o Expression evaluation (2 + 3 * 5).
o Function call history (Recursion).
o Undo-redo systems.
o Syntax parsing in compilers.
Program 5: Queue Implementation Using Array in Java
int[] queue = new int[5];

 Creates an array of size 5.


 This array is the container for the queue elements.

�int front = -1, rear = -1;

 front: Index of the first element.


 rear: Index of the last element.
 Both set to -1 means the queue is empty.

�void enqueue(int data)

 Adds a new element at the end of the queue.

java
CopyEdit
if (rear == queue.length - 1) {

 Checks if the queue is full.

java
CopyEdit
if (front == -1) front = 0;

 If inserting the first element, initialize front to 0.

java
CopyEdit
queue[++rear] = data;

 Increase rear first, then insert the element at that position.

�void dequeue()

 Removes the front-most element from the queue.


java
CopyEdit
if (front == -1 || front > rear) {

 Checks if the queue is empty (underflow condition).

java
CopyEdit
System.out.println(queue[front] + " removed from the queue");
front++;

 Prints and removes the first element by moving the front pointer ahead.

�void display()

 Prints the queue elements from front to rear.

�public static void main(String[] args)

 Calls methods for demo:


o Adds elements: enqueue(10), enqueue(20), enqueue(30).
o Displays the queue.
o Removes one element using dequeue().
o Displays the new state.

� Real-World Scenario
1�⃣ Ticket Counters / Queues at Shops

 First customer joins the line — enqueue.


 First customer served and leaves — dequeue.
 First In, First Out (FIFO) — exactly like real-world lines!

2�⃣ Printer Job Queue


 Print requests are added one after another.
 Printer serves them in the order they arrived.

Why Important?
 Queues are used in:
o CPU process scheduling.
o Print services.
o Real-life task lists.
o Messaging systems like WhatsApp, Kafka, RabbitMQ.

Program 6: Circular Queue Implementation Using Array in Java


int[] queue = new int[5];

 Creates an integer array of size 5.


 Fixed-size circular storage for the queue.

�int front = -1, rear = -1;

 front points to the first element.


 rear points to the last element.
 -1 means the queue is empty.

�void enqueue(int data)

 Adds a new item into the queue.

java
CopyEdit
if ((rear + 1) % queue.length == front) {

 Checks if the queue is full.


 In a circular queue:
When next position of rear is front — it means full.

java
CopyEdit
if (front == -1) front = 0;
 If inserting the first element, set front = 0.

java
CopyEdit
rear = (rear + 1) % queue.length;
queue[rear] = data;

 Rear moves to the next position in a circle.


 Example: if rear is at index 4, (4+1)%5 = 0 — goes back to 0.

�void dequeue()

 Removes the front-most element.

java
CopyEdit
if (front == -1) {

 If front == -1 — the queue is empty.

java
CopyEdit
if (front == rear) {

 If front and rear are the same: only 1 item was present.
 Reset both to -1 after deletion.

java
CopyEdit
front = (front + 1) % queue.length;

 Moves front forward in a circular way.

�void display()

 Prints the elements from front to rear, even when rear < front (circular).

java
CopyEdit
int i = front;
while (true) {
System.out.print(queue[i] + " ");
if (i == rear) break;
i = (i + 1) % queue.length;
}

 Uses a loop that wraps around if needed.


 Stops printing when i == rear.

� Real-World Scenario
1�⃣ Car Parking System

 Fixed number of parking spots.


 Cars come in a circular order, and empty slots are reused when cars leave.

2�⃣ Task Scheduling in CPUs

 Round-Robin Scheduling uses a Circular Queue.


 When the last task is reached, the processor goes back to the first task.

Circular Queue vs Normal Queue


Feature Normal Queue Circular Queue
Memory Usage Inefficient (space wasted) Efficient (reuses space)
Rear Movement Moves only forward Loops back to start
Used In Simple ticket lines CPU scheduling, Memory buffers

Why Is It Important?
 Prevents wasted space.
 Used in OS-level memory and process management.
 Perfect for queues where elements keep entering and exiting frequently.

Program 8: Doubly Linked List in Java


class Node

 Each node stores:


o data: the value.
o prev: points to the previous node.
o next: points to the next node.

This makes the list bidirectional.

�Node head = null;

 The head points to the first node of the list.


 If head == null, the list is empty.

�void insertAtEnd(int data)

 Adds a new node at the end.

java
CopyEdit
if (head == null) {
head = newNode;
}

 If the list is empty, the new node becomes the head.

java
CopyEdit
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.prev = temp;

 If not empty, traverse to the last node and link the new node both ways:
o temp.next = newNode
o newNode.prev = temp
�void deleteByValue(int value)

 Deletes a node with the specified value.

If the value is at the head:

java
CopyEdit
head = head.next;
if (head != null) {
head.prev = null;
}

 Adjust prev pointer to maintain the structure.

If the value is in the middle or end:

java
CopyEdit
temp.prev.next = temp.next;
if (temp.next != null) {
temp.next.prev = temp.prev;
}

 Reconnects the previous and next nodes — the node gets removed.

�void displayForward()

 Traverses from head to NULL, printing the list forward.

�void displayBackward()

 Starts from the last node and goes backward using prev.

� Real-World Scenario
1�⃣ Music Player Playlist:
 Skip Next or Previous track — both directions.
 Uses next and prev links.

2�⃣ Browser History Navigation:

 Forward and backward navigation between websites.

3�⃣ Image Viewer:

 Move left or right between photos in an album.

Why Doubly Linked List is Important?


 Allows two-way traversal (forward and backward).
 Faster deletion of nodes when their reference is known.
 Basis for:
o Browser History
o Undo-Redo systems
o Memory management in OS.

Program9: Tree Traversal

Node Class
java
CopyEdit
class Node {

Defines a blueprint for the tree’s individual unit — called a Node.

java
CopyEdit
int data;

Stores the actual data of the node (an integer).

java
CopyEdit
Node left, right;

Each node has two links: one to the left child and one to the right child.
java
CopyEdit
public Node(int item) {
data = item;
left = right = null;
}

A constructor to initialize the node's value and set both child pointers to null (meaning no child
yet).

2️⃣ BinaryTree Class


java
CopyEdit
class BinaryTree {

Creates the main class to manage the tree and its traversals.

java
CopyEdit
Node root;

Defines the top-most node of the tree. Initially, it’s null until you assign something to it.

3️⃣ Inorder Traversal


java
CopyEdit
void printInorder(Node node) {

Method to perform Inorder traversal — first Left, then Root, then Right.

java
CopyEdit
if (node == null)
return;

Base case for recursion: if the current node is null, do nothing and return.

java
CopyEdit
printInorder(node.left);

Recursive call to visit the left child first.

java
CopyEdit
System.out.print(node.data + " ");

Visit (print) the node’s data once the left side is done.

java
CopyEdit
printInorder(node.right);

Recursive call to visit the right child.

4️⃣ Preorder Traversal


java
CopyEdit
void printPreorder(Node node) {

Defines the Preorder traversal method — Root first, then Left, then Right.

java
CopyEdit
if (node == null)
return;

Base case: if no node, exit.

java
CopyEdit
System.out.print(node.data + " ");

First print the data of the node.

java
CopyEdit
printPreorder(node.left);

Visit the left subtree.

java
CopyEdit
printPreorder(node.right);

Visit the right subtree.

5️⃣ Postorder Traversal


java
CopyEdit
void printPostorder(Node node) {

Defines Postorder traversal — Left, Right, then Root.

java
CopyEdit
if (node == null)
return;

Base case for recursion.

java
CopyEdit
printPostorder(node.left);

First visit the left child.

java
CopyEdit
printPostorder(node.right);

Then visit the right child.

java
CopyEdit
System.out.print(node.data + " ");

Finally, process the root node.

6️⃣ Main Method


java
CopyEdit
public static void main(String[] args) {

Starting point of the Java program.

java
CopyEdit
BinaryTree tree = new BinaryTree();

Create an instance of BinaryTree.

java
CopyEdit
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);

Builds the following tree:

markdown
CopyEdit
1
/ \
2 3
/ \
4 5

7️⃣ Traversals Output


java
CopyEdit
System.out.println("Inorder traversal:");
tree.printInorder(tree.root);

Prints nodes in Inorder (expected output: 4 2 5 1 3).

java
CopyEdit
System.out.println("\nPreorder traversal:");
tree.printPreorder(tree.root);

Prints nodes in Preorder (expected output: 1 2 4 5 3).

java
CopyEdit
System.out.println("\nPostorder traversal:");
tree.printPostorder(tree.root);

Prints nodes in Postorder (expected output: 4 5 2 3 1).

�Real-Life Analogy

 Think of a tree as a family tree.


 Preorder: You visit the parent before the kids.
 Inorder: You visit the older sibling (left), then the parent, then the younger sibling
(right).
 Postorder: You check all the kids first, and only then the parent.
Program 10- Binary Search Tree — Insertion & Search Program

Node Class: Structure for Each Tree Node


java
CopyEdit
class Node {

Defines a class for nodes in the BST.

java
CopyEdit
int key;

Each node holds an integer value called key.

java
CopyEdit
Node left, right;

Each node has links to its left and right child.

java
CopyEdit
public Node(int item) {
key = item;
left = right = null;
}

A constructor that assigns a value (item) to the key and initializes left and right children to null
— meaning no children when the node is created.

2�⃣ BST Class: Tree Creation & Logic


java
CopyEdit
class BST {

Defines the main Binary Search Tree class.

java
CopyEdit
Node root;

Holds the reference to the tree’s top node (initially empty).

java
CopyEdit
BST() {
root = null;
}

Constructor: when you create a BST object, the root is set to null.

3�⃣ Insert Method: Public Method


java
CopyEdit
void insert(int key) {
root = insertRec(root, key);
}

This is a public method that initiates the insertion process by calling insertRec.
Every new number is inserted starting from the root.

4�⃣ insertRec Method: Recursive Helper for Insertion


java
CopyEdit
Node insertRec(Node root, int key) {

This method does the real work — it finds the correct place in the tree for the new node.

java
CopyEdit
if (root == null) {
root = new Node(key);
return root;
}

If the current node is null, this is the correct spot — create a new Node with the key.

java
CopyEdit
if (key < root.key)
root.left = insertRec(root.left, key);

If the key is smaller than the current node's key, insert it into the left subtree.

java
CopyEdit
else if (key > root.key)
root.right = insertRec(root.right, key);

If the key is larger, insert it into the right subtree.


java
CopyEdit
return root;

Return the unchanged node pointer, so that the tree links stay correct.

5�⃣ Search Method: Public Method


java
CopyEdit
boolean search(int key) {
return searchRec(root, key);
}

A public method that starts searching from the root.

6�⃣ searchRec Method: Recursive Search


java
CopyEdit
boolean searchRec(Node root, int key) {

Recursive helper that searches for a key in the tree.

java
CopyEdit
if (root == null)
return false;

If the current node is null, the key doesn't exist in the tree.

java
CopyEdit
if (root.key == key)
return true;

If the current node’s key matches the search key — success! Found it.

java
CopyEdit
return key < root.key ? searchRec(root.left, key) :
searchRec(root.right, key);

Ternary operator:

 If the key is less, search the left subtree.


 If greater, search the right subtree.

7�⃣ Main Method: Driver Code


java
CopyEdit
public static void main(String[] args) {

The starting point for Java execution.

java
CopyEdit
BST tree = new BST();

Creates a new Binary Search Tree.

�Building the Tree


java
CopyEdit
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

Inserts elements in this order, creating the following structure:

markdown
CopyEdit
50
/ \
30 70
/ \ / \
20 40 60 80

�Searching
java
CopyEdit
System.out.println(tree.search(40) ? "Found" : "Not Found");

Searches for the key 40. If found, prints Found.

java
CopyEdit
System.out.println(tree.search(25) ? "Found" : "Not Found");

Searches for 25. If not found, prints Not Found.

�Real-Life Analogy

Imagine a library's bookshelf where:

 Books are sorted alphabetically.


 If you’re looking for "Moby Dick" (key), you start at the middle shelf.
 If the middle book starts with "S", you know to check the left half.
 If it starts with "B", you know to check the right half.

This is exactly how a Binary Search Tree works — efficient, sorted, and easy to search.

Program 11- Graph using Adjacency Matrix

What’s an Adjacency Matrix?

In graph theory, an adjacency matrix is a 2D array (matrix[i][j]) where:

 matrix[i][j] = 1 means there is an edge from vertex i to vertex j.


 matrix[i][j] = 0 means there is no edge.

This is a neat way to represent unweighted and undirected or directed graphs.

Graph Class Definition


java
CopyEdit
class Graph {

Defines a class Graph that will hold the adjacency matrix and related functions.

2�⃣ Instance Variables


java
CopyEdit
private int[][] adjMatrix;
private int numVertices;
 adjMatrix: 2D array to store the edges between vertices.
 numVertices: the number of nodes (vertices) in the graph.

3�⃣ Constructor
java
CopyEdit
public Graph(int numVertices) {
this.numVertices = numVertices;
adjMatrix = new int[numVertices][numVertices];
}

 Accepts the total number of vertices.


 Initializes numVertices.
 Creates a numVertices x numVertices matrix filled with 0 by default (Java does this
automatically).

4�⃣ Add Edge Method


java
CopyEdit
public void addEdge(int i, int j) {
adjMatrix[i][j] = 1;
adjMatrix[j][i] = 1; // For undirected graph
}

 Adds an edge between vertex i and vertex j.


 Sets both [i][j] and [j][i] to 1 because this example assumes an undirected graph
(if you can go from i to j, you can also go back).

5�⃣ Remove Edge Method


java
CopyEdit
public void removeEdge(int i, int j) {
adjMatrix[i][j] = 0;
adjMatrix[j][i] = 0; // For undirected graph
}

 Removes an edge by resetting both positions to 0, meaning no connection.

6�⃣ Print Graph Method


java
CopyEdit
public void printGraph() {
System.out.println("Adjacency Matrix:");

Prints a header for the matrix.

java
CopyEdit
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
System.out.print(adjMatrix[i][j] + " ");
}
System.out.println();
}

Nested loops:

 Outer loop: runs for each vertex i.


 Inner loop: prints each adjMatrix[i][j] — either 1 (edge exists) or 0 (no edge).

7�⃣ Main Method


java
CopyEdit
public static void main(String[] args) {

Starting point of the Java program.

java
CopyEdit
Graph g = new Graph(4);

Creates a new graph with 4 vertices (labeled 0, 1, 2, 3).

�Adding Edges
java
CopyEdit
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);

Adds edges between the specified nodes:

 0 connected to 1 and 2.
 1 connected to 2.
 2 connected to 3.

�Printing the Graph


java
CopyEdit
g.printGraph();

Prints the adjacency matrix to visualize the connections.

Expected Output:

Adjacency Matrix:
0 1 1 0
1 0 1 0
1 1 0 1
0 0 1 0

Each 1 shows a direct connection between two vertices.

�Real-Life Analogy

 Think of the matrix as a map of cities.


 A 1 means a road exists between two cities.
 A 0 means no direct road.
 Adding or removing edges is like building or demolishing roads.

Program12- Hashing Using HashMap

Import Statement
java
CopyEdit
import java.util.HashMap;

 This imports the HashMap class from Java’s built-in java.util package.
 HashMap allows you to store data as key-value pairs.

2�⃣ Class Definition


java
CopyEdit
class HashingExample {

Defines a public class HashingExample.

3�⃣ Main Method


java
CopyEdit
public static void main(String[] args) {

Entry point for the Java application.

4�⃣ Create HashMap


java
CopyEdit
HashMap<Integer, String> map = new HashMap<>();

 Declares a HashMap named map.


 The Integer type is the key (like a unique ID).
 The String type is the value (like a name).
 HashMap uses hashing internally to store and retrieve data quickly (constant-time O(1)
in most cases).

5�⃣ Adding Elements


java
CopyEdit
map.put(101, "Alice");
map.put(102, "Bob");
map.put(103, "Charlie");
map.put(104, "Daisy");

 .put(key, value) method inserts data into the HashMap.


 If the key already exists, the old value gets replaced.
 Internally, the key 101 is hashed to find the correct bucket, and "Alice" is stored there.

6�⃣ Printing All Elements


java
CopyEdit
System.out.println("HashMap Elements:");
Prints a header.

java
CopyEdit
for (Integer key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}

 map.keySet() returns all the keys in the HashMap.


 The for-each loop goes through each key.
 map.get(key) fetches the value for that key.
 Prints all key-value pairs.

7�⃣ Searching a Key


java
CopyEdit
int searchKey = 102;

Defines a key to search for.

java
CopyEdit
if (map.containsKey(searchKey)) {
System.out.println("Found! Value: " + map.get(searchKey));
} else {
System.out.println("Key not found!");
}

 .containsKey(key) checks if a particular key exists.


 If found, prints the corresponding value.
 Otherwise, prints "Key not found!".

8�⃣ Removing a Key


java
CopyEdit
map.remove(103);

 .remove(key) deletes the key-value pair for key 103.


 The hash function locates the correct bucket, and the entry is removed.

9�⃣ Print After Deletion


java
CopyEdit
System.out.println("After Removing Key 103:");
System.out.println(map);

 Prints the entire HashMap after deletion.


 Shows all remaining key-value pairs.

��How Hashing Works Here

 When you call .put(), Java:


1. Computes the hash code of the key.
2. Uses that hash to determine the bucket location in memory.
3. Stores the key-value pair.
 .get() uses the same hash logic to directly jump to the bucket and retrieve the value.

This is why hashing gives you lightning-fast lookup, insertion, and deletion for keys!

�Real-Life Analogy

 Imagine an employee directory.


 101 = Employee ID, "Alice" = Employee Name.
 You store or search the employee info using the ID as the key.
 HashMap acts like a digital address book with automatic indexing using a hash.

Program 13- Bubble sort

Class Declaration
java
CopyEdit
class BubbleSort {

Defines a public class named BubbleSort where the sorting logic will live.

2�⃣ Bubble Sort Method


java
CopyEdit
void bubbleSort(int arr[]) {

Defines a method bubbleSort that takes an array of integers as input.


java
CopyEdit
int n = arr.length;

Stores the size of the array in variable n.

3�⃣ Outer Loop


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

 Runs n-1 times.


 After every complete pass, the largest element "bubbles up" to the correct position.
 So the number of passes needed is n-1.

4�⃣ Inner Loop


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

 This loop compares adjacent elements.


 n - i - 1 shortens the loop each pass since the last i elements are already sorted.

5�⃣ Swapping Logic


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

If the current element is larger than the next one, swap them.

java
CopyEdit
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;

 Temporarily stores arr[j] in temp.


 Assigns the next element to the current position.
 Places the temporary value into the next position.

This is the "bubble" action — the largest unsorted element moves to its correct position.
6�⃣ Print Array Method
java
CopyEdit
void printArray(int arr[]) {

A helper method to print the array elements.

java
CopyEdit
int n = arr.length;
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();

 Loops through the array.


 Prints each element separated by space.
 Moves to a new line at the end.

7�⃣ Main Method


java
CopyEdit
public static void main(String args[]) {

Starting point of the Java program.

8�⃣ Object Creation and Array Declaration


java
CopyEdit
BubbleSort ob = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};

 Creates an object ob of the class BubbleSort.


 Declares and initializes an unsorted array.

9�⃣ Printing Original Array


java
CopyEdit
System.out.println("Original Array:");
ob.printArray(arr);
Prints the array before sorting.

�Calling Bubble Sort


java
CopyEdit
ob.bubbleSort(arr);

Calls the bubbleSort method to sort the array.

�Printing Sorted Array


java
CopyEdit
System.out.println("Sorted Array:");
ob.printArray(arr);

Prints the sorted array after the sorting process.

�Real-Life Analogy

Imagine a lineup of students arranged by height but randomly shuffled. You start from the first
pair, compare them, and if the first one is taller, they swap places. You repeat this until the
tallest student walks to the end — just like a bubble rising to the top of water. That’s the
essence of Bubble Sort!

Program 14- Selection Sort

Class Declaration
java
CopyEdit
class SelectionSort {

Defines a class named SelectionSort.

2�⃣ Selection Sort Method


java
CopyEdit
void selectionSort(int arr[]) {
Defines a method selectionSort that takes an integer array arr as input.

3�⃣ Get Array Length


java
CopyEdit
int n = arr.length;

Stores the size of the array in variable n.

4�⃣ Outer Loop


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

 Runs from the start of the array to the second-last element.


 i marks the boundary between the sorted and unsorted parts of the array.
 After each loop, the smallest remaining element is placed at position i.

5�⃣ Assume Minimum Index


java
CopyEdit
int min_idx = i;

 Assume that the current index i holds the minimum value.


 min_idx stores the index of the smallest element found in the unsorted part.

6�⃣ Inner Loop


java
CopyEdit
for (int j = i + 1; j < n; j++) {

 Loop starts from i+1 (the unsorted part) and goes to the end.
 j scans the unsorted section for the smallest element.

7�⃣ Find Minimum Element


java
CopyEdit
if (arr[j] < arr[min_idx]) {
min_idx = j;
}

 Compares arr[j] with arr[min_idx].


 If a smaller element is found, update min_idx to j.

8�⃣ Swapping Elements


java
CopyEdit
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;

 Swaps the smallest element found with the element at index i.


 temp temporarily holds the smallest value.
 arr[min_idx] gets the value at i.
 arr[i] gets the minimum value.

9�⃣ Print Array Method


java
CopyEdit
void printArray(int arr[]) {

Defines a method to print all the elements of the array.

java
CopyEdit
int n = arr.length;
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();

Loops through each element and prints it, separated by spaces.

�Main Method
java
CopyEdit
public static void main(String args[]) {

Entry point of the Java program.


�Create Object and Array
java
CopyEdit
SelectionSort ob = new SelectionSort();
int arr[] = {64, 25, 12, 22, 11};

 Creates an object ob of class SelectionSort.


 Declares an unsorted array.

��Print Original Array


java
CopyEdit
System.out.println("Original Array:");
ob.printArray(arr);

Prints the array before sorting.

�Call Selection Sort


java
CopyEdit
ob.selectionSort(arr);

Calls the selectionSort method to sort the array.

�Print Sorted Array


java
CopyEdit
System.out.println("Sorted Array:");
ob.printArray(arr);

Prints the sorted array after sorting.

�Real-Life Analogy

Imagine a student organizing books by height.


They scan the entire shelf, find the shortest book, and place it at the start. Then move on to the
next and repeat — until the whole shelf is sorted!

You might also like