0% found this document useful (0 votes)
19 views99 pages

All Final

The document is a lab report on Data Structures and Algorithms, detailing various experiments related to arrays and linked lists, including algorithms for summing array elements, finding unique elements, sorting strings, and checking for palindromes. Each experiment includes aims, algorithms, source code in Java, and results indicating successful execution. The report also covers the implementation of sorting algorithms and matrix operations.

Uploaded by

jasmithapilla
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)
19 views99 pages

All Final

The document is a lab report on Data Structures and Algorithms, detailing various experiments related to arrays and linked lists, including algorithms for summing array elements, finding unique elements, sorting strings, and checking for palindromes. Each experiment includes aims, algorithms, source code in Java, and results indicating successful execution. The report also covers the implementation of sorting algorithms and matrix operations.

Uploaded by

jasmithapilla
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/ 99

Data Structures and Algorithms.

Lab-Report

TABLE OF CONTENTS

S.NO EXP.NO EXPERIMENT NAME MARKS SIGN

1 1 ARRAYS

a. Sum of all array elements

b. Single elements among doubles

c. Rearrange even position that are greater


than odd

d. Sorting of strings

e. Array rotation left by n positions

f. Check palindrome or not

g. Find the frequency of each element

h. Multiplication table in 2D array

i. Count even numbers in nD array

j. Matrix Multiplication

k. Store & display books categorised by


sections and shelves in 3D array

2 2 Implementation of Linked List

a. Singly Linked List

b. Doubly Linked list

c. Circular Singly Linked list

d. Circular Doubly Linked List

3 3 Sorting Algorithms

a. Bubble Sort
b. Insertion Sort

c. Selection Sort

d. Merge Sort

e. Quick Sort

4 4 Working with Linked List

a. Swap the pair of nodes in linked list

b. Reverse the linked list except head and tail

5 5 Working with both arrays and linked list

a. Rearrange Student name in linked list


based on the Roll.no in an array

TOTAL MARKS

AVERAGE

Exp. no: Arrays

a) Sum of all Array Elements

Aim:

To write a JAVA program to find the sum of all arrary elements

ALGORITHM:
Step 1: Start the Program.

Step 2: Get the size of the array from the user as input.

Step 3: Get the array elements based on the array size using for() loop.

Step 4: Declare the variable sum as 0.

Step 5: Iterate through each element of the array and add each element to the variable
sum.

Step 6: Display the sum.

Source Code:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

class Main {

public static void main(String[] args) throws Exception {

Bu eredReader b= new Bu eredReader(new InputStreamReader(System.in));

System.out.println("Enter the size:");

int size= Integer.parseInt(b.readLine());

int sum=0;

int arr[]= new int[size];

System.out.println("Enter the array values:");

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

arr[i]= Integer.parseInt(b.readLine());

sum+=arr[i];

System.out.println("The sum of the array is " + sum);

}
OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

b) Single element among doubles

Aim:

To write a JAVA program to find the Single element among the doubles from the array.

ALGORITHM:

Step 1: Start the Program.

Step 2: Get the size of the array from the user as input.

Step 3: Create an integer array of the given size.

Step 4: Get the array elements from the user and store them in the array.

Step 5: Initialize a variable x to store the value that occurs only once in the array.

Step 6: Start iterating through the array. For each element at index i:

 Initialize a count variable to 0.

 For each element at index j (starting from i+1), compare the elements.

 If the element at index i is found at index j, increment the count.


Step 7: If the count for an element at index i is 0 (i.e., it doesn’t appear again in the array),
set the value of x to the element at index i and break the loop.

Step 8: Display the value stored in x which is the element that occurs once in the array.

Step 9: End the Program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

class Main {

public static void main(String[] args) throws Exception {

Bu eredReader b= new Bu eredReader(new InputStreamReader(System.in));

System.out.println("Enter the size:");

int size= Integer.parseInt(b.readLine());

int arr[]= new int[size];

int i, j, x=0;

System.out.println("Enter the array values:");

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

arr[i]= Integer.parseInt(b.readLine());

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

int count=0;

for(j=i+1; j< size; j++){

if (arr[i] == arr[j]){

count++;
}

if(count == 0){

x = arr[i];

break;

System.out.println("Value that occured once is "+ x);

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

c) Rearrange that even positioned are greater than odd

Aim:
To write a JAVA program to Rearrange the array in that even positioned are greater than
odd.

ALGORITHM:

Step 1: Start the Program.

Step 2: Get the size of the array from the user as input.

Step 3: Create an integer array of the given size.

Step 4: Get the array elements from the user and store them in the array.

Step 5: Iterate through the array with the outer loop i incrementing by 2 (i.e., at even
positions):

 Inside this loop, iterate through the rest of the array starting from i+1 and
incrementing by 2 (i.e., considering only elements at odd positions).

 Compare the element at position i with the element at position j.

 If the element at index i is greater than the element at index j, swap the values of
arr[i] and arr[j].

Step 6: After sorting the elements at even positions to ensure they are greater than the
odd-positioned elements, print the modified array.

Step 7: End the Program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

class Main {

public static void main(String[] args) throws Exception {

Bu eredReader b= new Bu eredReader(new InputStreamReader(System.in));

System.out.println("Enter the size:");

int size= Integer.parseInt(b.readLine());

int arr[]= new int[size];


int i, j, x=0;

System.out.println("Enter the array values:");

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

arr[i]= Integer.parseInt(b.readLine());

for (i=0; i< size; i+=2){

for(j=i+1; j< size; j+=2){

if (arr[i] > arr[j]){

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

System.out.println("Even Positioned Greater Array:");

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

System.out.println(arr[i]);

OUTPUT:
RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

d) Sort a String Array without using sort()

Aim:

To write a JAVA program to Sort a string array without using the sort () function.

ALGORITHM:

Step 1: Start the program.

Step 2: Prompt the user to input the size of the string array.

Step 3: Create an array of strings with the specified size.

Step 4: Prompt the user to enter the strings, and store them in the array.

Step 5: Print the array of strings before sorting.

Step 6: Perform Bubble Sort to arrange the strings in ascending lexicographical order:

 Iterate through the array, comparing each adjacent pair of strings.

 If the string at the current position is lexicographically greater than the next string,
swap them.

 Repeat this process for the entire array.


Step 7: Print the array of strings after sorting.

Step 8: End the program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

class Main {

public static void main(String[] args) throws Exception {

Bu eredReader b= new Bu eredReader(new InputStreamReader(System.in));

System.out.println("Enter the size of the string array:");

int size = Integer. parseInt(b.readLine());

String a[]= new String[size];

System.out.println("Enter the strings:");

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

a[i]= b.readLine();

System.out.println("Before sorting:");

for(String i:a){

System.out.println(i);

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

for(int j=0; j< size-1; j++) {

if(a[j].compareTo(a[j+1])> 0){

String temp = a[j];

a[j] = a[j+1];
a[j+1]= temp;

System.out.println("After Sorting:");

for (String i : a) {

System.out.println(i);

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

e) Rotate the array to the left by n positions

Aim:
To write a JAVA program to Rotate the array to the left by n positions.

ALGORITHM:

Step 1: Start the program.

Step 2: Prompt the user to input the size of the string array.

Step 3: Create an array of strings with the specified size.

Step 4: Prompt the user to enter the strings, and store them in the array.

Step 5: Print the array of strings before rotation.

Step 6: Prompt the user to input the number of positions to rotate the array.

Step 7: Adjust the number of positions to rotate (r) by performing modulo operation: r = r %
size.

Step 8: Reverse the first r elements of the array using the helper function reverse.

Step 9: Reverse the remaining elements (from index r to the last element) of the array using
the helper function reverse.

Step 10: Reverse the entire array (from the first element to the last) using the helper
function reverse.

Step 11: Print the array of strings after rotation.

Step 12: End the program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

class Main {

public static void main(String[] args) throws Exception {

Bu eredReader b= new Bu eredReader(new InputStreamReader(System.in));

System.out.println("Enter the size of the string array:");

int size = Integer. parseInt(b.readLine());

String a[]= new String[size];


System.out.println("Enter the strings:");

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

a[i]= b.readLine();

System.out.println("Before Rotation:");

for(String i:a){

System.out.println(i);

System.out.println("Enter the no of positions to rotate:");

int r= Integer.parseInt(b.readLine());

r = r % size;

reverse(a, 0, r-1);

reverse(a, r, size-1);

reverse(a, 0, size-1);

System.out.println("After Rotation:");

for(String i:a){

System.out.println(i);

public static void reverse(String a[], int low, int high ){

while(low< high){

String temp = a[low];

a[low]= a[high];

a[high] = temp;

low++;

high--;
}

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

f) To Check whether Palindrome or not

Aim:

To write a JAVA program to find out whether palindrome or not for the string array.

Algorithm:

1. Start the Program.

2. Input the string:

a. Accept the string from the user.


3. Initialize Variables:

a. Set a boolean variable y = true (assume the string is a palindrome).

b. Get the length of the string and store it in z.

4. Loop through the string (halfway):

a. For each index i from 0 to z/2 - 1:

i. Compare the character at position i (from the start) with the character at position z -
1 - i (from the end).

ii. If the characters do not match, set y = false and exit the loop.

5. Check Palindrome Status:

a. If y is true (no mismatch found), the string is a palindrome.

i. Print: The string is a palindrome.

b. Otherwise, if y is false (mismatch found), the string is not a palindrome.

i. Print: The string is not a palindrome.

6. End the Program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

public class Main {

public static void main(String[] args) throws Exception {

Bu eredReader b= new Bu eredReader(new InputStreamReader(System.in));

String x= b.readLine();

Boolean y= true;

int z= x.length();

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

if(x.charAt(i) != x.charAt(z-1)){
y= false;

break;

else

System.out.println(x + "is a palindrome");

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

g) Finding the frequency of each element in the array

Aim:

To write a JAVA program to find the frequency of each element in the array.

Algorithm:

1. Start the Program.

2. Input the string:

a. Accept the string from the user.

3. Initialize Variables:

a. Set a boolean variable y = true (assume the string is a palindrome).


b. Get the length of the string and store it in z.

4. Loop through the string (halfway):

a. For each index i from 0 to z/2 - 1:

i. Compare the character at position i (from the start) with the character at position z -
1 - i (from the end).

ii. If the characters do not match, set y = false and exit the loop.

5. Check Palindrome Status:

a. If y is true (no mismatch found), the string is a palindrome.

i. Print: The string is a palindrome.

b. Otherwise, if y is false (mismatch found), the string is not a palindrome.

i. Print: The string is not a palindrome.

6. End the Program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

public class Main {

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.print("Enter the number of elements: ");

int n = Integer.parseInt(br.readLine());

int[] arr = new int[n];

boolean[] visit = new boolean[n];

System.out.println("Enter the elements:");

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


arr[i] = Integer.parseInt(br.readLine());

visit[i] = false;

System.out.println("Element Frequencies:");

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

if (visit[i]) {

continue;

int count = 1;

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

if (arr[i] == arr[j]) {

count++;

visit[j] = true;

System.out.println(arr[i] + "-" + count);

OUTPUT:
RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

h) Multiplication Table in a 2D array with 10 columns

Aim:

To write a JAVA program to print Multiplication table in a 2D array with 10 columns.

ALGORITHM:

Step 1: Start the Program.

Step 2: Input the Number of Rows:

 Prompt the user to enter the number of rows.

 Store the input in a variable row.

Step 3: Initialize Number of Columns:

 Set the number of columns to 10 (constant value col = 10).

Step 4: Declare and Initialize the 2D Array:

 Declare a 2D array arr with dimensions row x col.

Step 5: Fill the Array:

 For each row i from 0 to row-1:


o For each column j from 0 to col-1:

 Set arr[i][j] = (i + 1) * (j + 1).

Step 6: Display the Array:

 Print "Generated 2D Array".

 For each row i from 0 to row-1:

o For each column j from 0 to col-1:

 Print arr[i][j] followed by a tab.

o Print a new line after each row.

Step 7: End the Program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

public class Main {

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.print("Enter number of rows: ");

int row = Integer.parseInt(br.readLine());

int col = 10;

int[][] arr = new int[row][col];

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


for (int j = 0; j < col; j++) {

arr[i][j] = (i + 1) * (j + 1);

System.out.println("Generated 2D Array:");

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

for (int j = 0; j < col; j++) {

System.out.print(arr[i][j] + "\t ");

System.out.println();

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed
i) Counting the even numbers in a nD array

Aim:

To write a JAVA program to Counting the even numbers in a 1D array.

ALGORITHM:

Step 1: Start the Program.

Step 2: Input the Number of Layers (Depth):

 Prompt the user to enter the number of layers (depth).

 Store the input in a variable depth.

Step 3: Input the Number of Rows:

 Prompt the user to enter the number of rows.

 Store the input in a variable rows.

Step 4: Input the Number of Columns:

 Prompt the user to enter the number of columns.

 Store the input in a variable cols.

Step 5: Declare and Initialize the 3D Array:

 Declare a 3D array arr with dimensions [depth][rows][cols].

Step 6: Input Elements for the 3D Array:

 For each layer i from 0 to depth - 1:

o Prompt the user to enter values for each row in the current layer.

o For each row j from 0 to rows - 1:

 For each column k from 0 to cols - 1:

 Store the entered values into arr[i][j][k].

Step 7: Count Even Numbers:

 Initialize a variable count as 0.

 For each layer i from 0 to depth - 1:

o For each row j from 0 to rows - 1:


 For each column k from 0 to cols - 1:

 If arr[i][j][k] is even (i.e., arr[i][j][k] % 2 == 0), increment the count.

Step 8: Display the Count of Even Numbers:

 Print the count of even numbers in the 3D array.

Step 9: End the Program.

SOURCE CODE

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

public class Main{

public static void main(String[] args) throws IOException{

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));


System.out.print("Enter the number of layers (depth): ");

int depth = Integer.parseInt(br.readLine());

System.out.print("Enter the number of rows: ");

int rows = Integer.parseInt(br.readLine());

System.out.print("Enter the number of columns: ");

int cols = Integer.parseInt(br.readLine());

int[][][] arr = new int[depth][rows][cols];

System.out.println("Enter the elements of the 3D array:");

for (int i = 0; i < depth; i++);

System.out.println("Layer " + (i + 1) + ":");

for (int j = 0; j < rows; j++) {

String[] input = br.readLine().split(" ");

for (int k = 0; k < cols; k++) {


arr[i][j][k] = Integer.parseInt(input[k])

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

for (int j = 0; j < rows; j++) {

for (int k = 0; k < cols; k++) {

if (arr[i][j][k] % 2 == 0) {

count++;

System.out.println("Count of even numbers: " + count);

OUTPUT:
RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

j) Matrix Multiplication

Aim:

To write a JAVA program to print a matrix Multiplication of two matrix.

ALGORITHM:

Step 1: Start the Program.

Step 2: Input Matrix Dimensions:

 Prompt the user to input the number of rows m for Matrix A.

 Prompt the user to input the number of columns n for Matrix A and rows n for Matrix
B (since the number of columns of Matrix A should be equal to the number of rows
of Matrix B).

 Prompt the user to input the number of columns p for Matrix B.

Step 3: Declare and Initialize Matrices:


 Declare Matrix A with dimensions [m][n].

 Declare Matrix B with dimensions [n][p].

 Declare Matrix C with dimensions [m][p] (to store the result of the multiplication).

Step 4: Input Elements for Matrix A:

 For each row i from 0 to m - 1:

o Prompt the user to enter the elements for the row, and split the input string into an
array.

o For each column j from 0 to n - 1, assign the values from the input array to A[i][j].

Step 5: Input Elements for Matrix B:

 For each row i from 0 to n - 1:

o Prompt the user to enter the elements for the row, and split the input string into an
array.

o For each column j from 0 to p - 1, assign the values from the input array to B[i][j].

Step 6: Multiply Matrices A and B:

 For each row i from 0 to m - 1:

o For each column j from 0 to p - 1:

 Initialize C[i][j] to 0.

 For each element k from 0 to n - 1:

 Multiply A[i][k] and B[k][j] and add the result to C[i][j].

Step 7: Display the Resultant Matrix:

 For each row i from 0 to m - 1:

o For each column j from 0 to p - 1, print the value of C[i][j].

 Print the resulting matrix C.

Step 8: End the Program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;
import java.io.IOException;

public class Main {

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.print("Enter number of rows for Matrix A: ");

int m = Integer.parseInt(br.readLine());

System.out.print("Enter number of columns for Matrix A (rows for Matrix B): ");

int n = Integer.parseInt(br.readLine());

System.out.print("Enter number of columns for Matrix B: ");

int p = Integer.parseInt(br.readLine());

int[][] A = new int[m][n];

int[][] B = new int[n][p];

int[][] C = new int[m][p];

System.out.println("Enter elements of Matrix A:");

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

String[] input = br.readLine().split(" ");

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

A[i][j] = Integer.parseInt(input[j]);

System.out.println("Enter elements of Matrix B:");

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


String[] input = br.readLine().split(" ");

for (int j = 0; j < p; j++) {

B[i][j] = Integer.parseInt(input[j]);

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

for (int j = 0; j < p; j++) {

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

C[i][j] += A[i][k] * B[k][j];

System.out.println("Resultant Matrix (AxB):");

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

for (int j = 0; j < p; j++) {

System.out.print(C[i][j] + " ");

System.out.println();

OUTPUT:
RESULT:

Thus all the JAVA programs to practice the implementation and usage of arrays have been
successfully executed

i)Store & display library books categorized by sections and shelves 3D array

Aim:

To write a JAVA program to Store and display lib books categorized by sections and
shelves 3D array.

ALGORITHM:

Step 1: Start the Program.

Step 2: Input the number of sections S in the library.

Step 3: For each section:

 Input the number of shelves in the section.

 For each shelf:

o Input the number of books.

o For each book, input the book title.

Step 4: Display the library collection by section, shelf, and book.

Step 5: End the Program.


SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

public class Main {

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.print("Enter number of sections in the library: ");

int S = Integer.parseInt(br.readLine());

String[][][] books = new String[S][][];

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

System.out.print("Enter number of shelves in Section " + (i + 1) + ": ");

int SH = Integer.parseInt(br.readLine());

books[i] = new String[SH][];

for (int j = 0; j < SH; j++) {

System.out.print("Enter number of books in Shelf " + (j + 1) + " of Section " + (i + 1) +


": ");

int B = Integer.parseInt(br.readLine());

books[i][j] = new String[B];

System.out.println("Enter the titles of " + B + " books:");


for (int k = 0; k < B; k++) {

books[i][j][k] = br.readLine();

System.out.println("\nLibrary Book Collection:");

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

System.out.println("Section " + (i + 1) + ":");

for (int j = 0; j < books[i].length; j++) {

System.out.println(" Shelf " + (j + 1) + ":");

for (int k = 0; k < books[i][j].length; k++) {

System.out.println(" " + books[i][j][k]);

OUTPUT:
RESULT:

Thus, all the JAVA programs to practice the implementation and usage of Arrays
have been successfully executed.

Exp. no: Implementation of Linked List

a) Singly Linked List

AIM:
To implement a Singly Linked List in Java that allows performing basic operations such
as:

1. Insertion at the beginning, end, and specific position.

2. Deletion from the beginning, end, and specific position.

3. Searching for an element.

4. Updating an element.

5. Displaying the list and getting the size.

Algorithm:

Step 1: Initialize an empty Singly Linked List.

Step 2: Provide operations to the user:

1. Insert First:
Create a new node, point it to the current head, then update head.

2. Insert Last:
Create a new node, traverse to the last node, link it to the new node.

3. Insert at Index:
Traverse to the (index - 1) node, link the new node in between.

4. Delete First:
Update head to head.next.

5. Delete Last:
Traverse to second last node, set its next to null.

6. Delete at Index:
Traverse to (index - 1) node, skip the next node in the link.

7. Search:
Traverse the list, check if any node's data matches the key.

8. Update:
Traverse and replace the value of the matching node.
9. Get Size:
Traverse the list, count nodes, return count.

10. Display:
Traverse from head, print each node’s data.

Step 3: Based on user input, perform the desired operation.

Step 4: Exit if the user chooses to exit.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

class Node {

int data;

Node next;

public Node(int data) {

this.data = data;

this.next = null;

public class SinglyLinkedList {

Node head;

int size = 0;

public void insertFirst(int data) {

Node newNode = new Node(data);


newNode.next = head;

head = newNode;

size++;

public void insertLast(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;

} else {

Node temp = head;

while (temp.next != null) {

temp = temp.next;

temp.next = newNode;

size++;

public void insertAtIndex(int data, int index) {

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

System.out.println("Invalid Index!");

return;

if (index == 0) {

insertFirst(data);
return;

Node newNode = new Node(data);

Node temp = head;

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

temp = temp.next;

newNode.next = temp.next;

temp.next = newNode;

size++;

public void deleteFirst() {

if (head == null) {

System.out.println("List is empty!");

return;

head = head.next;

size--;

public void deleteLast() {

if (head == null) {

System.out.println("List is empty!");

return;

}
if (head.next == null) {

head = null;

} else {

Node temp = head;

while (temp.next.next != null) {

temp = temp.next;

temp.next = null;

size--;

public void deleteAtIndex(int index) {

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

System.out.println("Invalid Index!");

return;

if (index == 0) {

deleteFirst();

return;

Node temp = head;

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

temp = temp.next;

temp.next = temp.next.next;
size--;

public boolean search(int key) {

Node temp = head;

while (temp != null) {

if (temp.data == key) {

return true;

temp = temp.next;

return false;

public void update(int oldVal, int newVal) {

Node temp = head;

while (temp != null) {

if (temp.data == oldVal) {

temp.data = newVal;

return;

temp = temp.next;

System.out.println("Value not found in the list.");

}
public int getSize() {

return size;

public void display() {

if (head == null) {

System.out.println("List is empty.");

return;

Node temp = head;

System.out.print("Linked List: ");

while (temp != null) {

System.out.print(temp.data + " -> ");

temp = temp.next;

System.out.println("NULL");

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

SinglyLinkedList list = new SinglyLinkedList();

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Insert at First");

System.out.println("2. Insert at Last");


System.out.println("3. Insert at Index");

System.out.println("4. Delete First");

System.out.println("5. Delete Last");

System.out.println("6. Delete at Index");

System.out.println("7. Search");

System.out.println("8. Update");

System.out.println("9. Get Size");

System.out.println("10. Display");

System.out.println("11. Exit");

System.out.print("Enter your choice: ");

int choice = Integer.parseInt(br.readLine());

switch (choice) {

case 1:

System.out.print("Enter value to insert at first: ");

int val1 = Integer.parseInt(br.readLine());

list.insertFirst(val1);

break;

case 2:

System.out.print("Enter value to insert at last: ");

int val2 = Integer.parseInt(br.readLine());

list.insertLast(val2);

break;

case 3:
System.out.print("Enter value to insert: ");

int val3 = Integer.parseInt(br.readLine());

System.out.print("Enter index: ");

int index = Integer.parseInt(br.readLine());

list.insertAtIndex(val3, index);

break;

case 4:

list.deleteFirst();

break;

case 5:

list.deleteLast();

break;

case 6:

System.out.print("Enter index to delete: ");

int delIndex = Integer.parseInt(br.readLine());

list.deleteAtIndex(delIndex);

break;

case 7:

System.out.print("Enter value to search: ");

int searchVal = Integer.parseInt(br.readLine());

if (list.search(searchVal)) {

System.out.println(searchVal + " is found in the list.");


} else {

System.out.println(searchVal + " is not in the list.");

break;

case 8:

System.out.print("Enter value to update: ");

int oldVal = Integer.parseInt(br.readLine());

System.out.print("Enter new value: ");

int newVal = Integer.parseInt(br.readLine());

list.update(oldVal, newVal);

break;

case 9:

System.out.println("Size of Linked List: " + list.getSize());

break;

case 10:

list.display();

break;

case 11:

System.out.println("Exiting...");

return;

default:
System.out.println("Invalid choice! Please enter a valid option.");

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of linked list have
been successfully executed

b) Doubly Linked List

AIM:
To implement a Doubly Linked List in Java that supports:

1. Insertion at beginning, end, and any position

2. Deletion from beginning, end, and any position

3. Searching and updating an element

4. Displaying the list and getting its size

Algorithm:

Step 1: Initialize an empty Singly Linked List.

Step 2: Provide operations to the user:

 Insert First: Create a new node, set it as head and link the old head.

 Insert Last: Create a new node, set it as tail and link the previous tail.

 Insert at Index: Traverse to the index, adjust pointers of surrounding nodes.

 Delete First: Update head to the next node.

 Delete Last: Update tail to the previous node.

 Delete at Index: Traverse to index and adjust surrounding node pointers.

 Search: Traverse the list and check if node's value matches key.

 Update: Traverse and update the value of the matching node.

 Get Size: Return the current size of the list.

 Display Forward: Traverse from head to tail, print values.

 Display Backward: Traverse from tail to head, print values.

 Exit: Exit the program.

Step 3: Based on user input, perform the desired operation.

Step 4: Exit if the user chooses to exit

SOURCE CODE:

import java.io.InputStreamReader;

import java.io.IOException;
class Node {

int data;

Node prev, next;

public Node(int data) {

this.data = data;

this.prev = null;

this.next = null

public class DoublyLinkedList {

Node head, tail;

int size = 0;

public void insertFirst(int data) {

Node newNode = new Node(data);

if (head == null)

head = tail = newNode;

} else {

newNode.next = head;

head.prev = newNode;

head = newNode;

size++;

public void insertLast(int data) {

Node newNode = new Node(data);

if (tail == null) {
head = tail = newNode;

} else {

tail.next = newNode;

newNode.prev = tail;

tail = newNode; }

size++;

public void insertAtIndex(int data, int index) {

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

System.out.println("Invalid Index!");

return;

size++;

public void insertAtIndex(int data, int index) {

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

System.out.println("Invalid Index!");

return;

if (index == 0) {

insertFirst(data);

return;

}
if (index == size) {

insertLast(data);

return;

Node newNode = new Node(data);

Node temp = head;

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

temp = temp.next;

newNode.next = temp.next;

newNode.prev = temp;

temp.next.prev = newNode;

temp.next = newNode;

size++;

public void deleteFirst() {

if (head == null) {

System.out.println("List is empty!");

return;

if (head == tail) {

head = tail = null;

} else {

head = head.next;

head.prev = null;
}

size--;

public void deleteLast() {

if (tail == null) {

System.out.println("List is empty!");

return;

if (head == tail) {

head = tail = null;

} else {

tail = tail.prev;

tail.next = null;

size--;

public void deleteAtIndex(int index) {

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

System.out.println("Invalid Index!");

return;

if (index == 0) {

deleteFirst();

return;
}

if (index == size - 1) {

deleteLast();

return;

Node temp = head;

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

temp = temp.next;

temp.prev.next = temp.next;

temp.next.prev = temp.prev;

size--;

public boolean search(int key) {

Node temp = head;

while (temp != null) {

if (temp.data == key) {

return true;

temp = temp.next;

return false;

public void update(int oldVal, int newVal) {


Node temp = head;

while (temp != null) {

if (temp.data == oldVal) {

temp.data = newVal;

return;

temp = temp.next;

System.out.println("Value not found in the list.");

public int getSize() {

return size;

public void displayForward() {

if (head == null) {

System.out.println("List is empty.");

return;

Node temp = head;

System.out.print("Forward: ");

while (temp != null) {

System.out.print(temp.data + " ⇄ ");

temp = temp.next;

}
System.out.println("NULL");

public void displayBackward() {

if (tail == null) {

System.out.println("List is empty.");

return;

Node temp = tail;

System.out.print("Backward: ");

while (temp != null) {

System.out.print(temp.data + " ⇄ ");

temp = temp.prev;

System.out.println("NULL");

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

DoublyLinkedList list = new DoublyLinkedList();

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Insert at First");

System.out.println("2. Insert at Last");

System.out.println("3. Insert at Index");


System.out.println("4. Delete First");

System.out.println("5. Delete Last");

System.out.println("6. Delete at Index");

System.out.println("7. Search");

System.out.println("8. Update");

System.out.println("9. Get Size");

System.out.println("10. Display Forward");

System.out.println("11. Display Backward");

System.out.println("12. Exit");

System.out.print("Enter your choice: ");

int choice = Integer.parseInt(br.readLine());

switch (choice) {

case 1:

System.out.print("Enter value to insert at first: ");

int val1 = Integer.parseInt(br.readLine());

list.insertFirst(val1);

break;

case 2:

System.out.print("Enter value to insert at last: ");

int val2 = Integer.parseInt(br.readLine());

list.insertLast(val2);

break;

case 3:
System.out.print("Enter value to insert: ");

int val3 = Integer.parseInt(br.readLine());

System.out.print("Enter index: ");

int index = Integer.parseInt(br.readLine());

list.insertAtIndex(val3, index);

break;

case 4:

list.deleteFirst();

break;

case 5:

list.deleteLast();

break;

case 6:

System.out.print("Enter index to delete: ");

int delIndex = Integer.parseInt(br.readLine());

list.deleteAtIndex(delIndex);

break;

case 7:

System.out.print("Enter value to search: ");

int searchVal = Integer.parseInt(br.readLine());

if (list.search(searchVal)) {

System.out.println(searchVal + " is found in the list.");


} else {

System.out.println(searchVal + " is not in the list.");

break;

case 8:

System.out.print("Enter value to update: ");

int oldVal = Integer.parseInt(br.readLine());

System.out.print("Enter new value: ");

int newVal = Integer.parseInt(br.readLine());

list.update(oldVal, newVal);

break;

case 9:

System.out.println("Size of Doubly Linked List: " + list.getSize());

break;

case 10:

list.displayForward();

break;

case 11:

list.displayBackward();

break;

case 12:
System.out.println("Exiting...");

return;

default:

System.out.println("Invalid choice! Please enter a valid option.");

OUTPUT:

RESULT:
Thus all the JAVA programs to practice the implementation and usage of linked list have
been successfully executed

c) Circular Singly Linked list

AIM:

To implement a Circular Singly Linked List in Java that supports:

1. Insertion at a specific index

2. Deletion at a specific index

3. Displaying elements starting from a specific index

Algorithm:

Step 1: Initialize an empty Circular Singly Linked List.

Step 2: Provide operations to the user:Insert at Index

 If invalid index → error.

 If empty → head = tail = node, tail.next = head.

 If index 0 → insert at front, update tail.next.

 Else → insert at (index), update tail if at end.

Delete at Index

 If invalid → error.

 If one node → head = tail = null.

 If index 0 → move head, update tail.next.

 Else → skip node, update tail if needed.

Display from Index

 If invalid/empty → error.
 Go to index, loop with do-while until back to start.

Step 3: Based on user input, perform the desired operation.

Step 4: Exit if the user chooses to exit.import java.io.Bu eredReader;

SOURCE CODE:

import java.io.InputStreamReader;

import java.io.IOException;

class Node {

int data;

Node next;

Node(int data) {

this.data = data;

this.next = null;

public class CircularSinglyLinkedList {

Node head = null;

Node tail = null;

int size = 0;

public void insertAtIndex(int data, int index) {

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

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

Node newNode = new Node(data);

if (head == null) {

head = tail = newNode;

newNode.next = head;

} else if (index == 0) {

newNode.next = head;

head = newNode;

tail.next = head;

} else {

Node temp = head;

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

temp = temp.next;

newNode.next = temp.next;

temp.next = newNode;

if (index == size) {

tail = newNode;

tail.next = head;

size++;

}
public void deleteAtIndex(int index) {

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

System.out.println("Invalid index!");

return;

if (head == tail) {

head = tail = null;

} else if (index == 0) {

head = head.next;

tail.next = head;

} else {

Node temp = head;

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

temp = temp.next;

temp.next = temp.next.next;

if (index == size - 1) {

tail = temp;

tail.next = head;

size--;

}
public void displayFromIndex(int index) {

if (head == null || index < 0 || index >= size) {

System.out.println("Invalid index or list is empty!");

return;

Node temp = head;

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

temp = temp.next;

Node start = temp;

System.out.print("Circular List from index " + index + ": ");

do {

System.out.print(temp.data + " -> ");

temp = temp.next;

} while (temp != start);

System.out.println("(back to start)");

public static void main(String[] args) throws IOException {

CircularSinglyLinkedList list = new CircularSinglyLinkedList();

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

while (true) {
System.out.println("\n--- Circular Singly Linked List ---");

System.out.println("1. Insert at Index");

System.out.println("2. Delete at Index");

System.out.println("3. Display from Index");

System.out.println("4. Exit");

System.out.print("Choose an option: ");

int choice = Integer.parseInt(br.readLine());

switch (choice) {

case 1:

System.out.print("Enter value: ");

int val = Integer.parseInt(br.readLine());

System.out.print("Enter index to insert: ");

int idx = Integer.parseInt(br.readLine());

list.insertAtIndex(val, idx);

break;

case 2:

System.out.print("Enter index to delete: ");

int del = Integer.parseInt(br.readLine());

list.deleteAtIndex(del);

break;

case 3:

System.out.print("Enter index to start display: ");

int disp = Integer.parseInt(br.readLine());


list.displayFromIndex(disp);

break;

case 4:

System.out.println("Exiting...");

return;

default:

System.out.println("Invalid choice!");

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of linked list have
been successfully executed
d) Circular Doubly Linked List

AIM:

To implement a Circular Doubly Linked List in Java that supports:

1. Insertion at any index

2. Deletion at any index

3. Displaying elements in forward and backward directions from a specific index

Step 1: Initialize an empty Circular Doubly Linked List.

Step 2: Provide operations to the user:

Insert at Index

1. If index invalid → print error.

2. If list empty → head = newNode, link to itself (prev & next).

3. If index = 0 → insert before head, update tail and head.

4. Else → go to (index - 1), insert between nodes.

Delete at Index

1. If invalid or empty → print error.

2. If size = 1 → head = null.

3. If index = 0 → move head to next, update tail links.

4. Else → go to index, remove node by fixing prev and next.

Display Forward from Index

1. If list empty or index invalid → print error.

2. Go to index node.

3. Loop with do-while printing next until back to start.


Display Backward from Index

1. Same as above, but loop with prev.

Step 3: Based on user input, perform the desired operation.

Step 4: Exit if the user chooses to exit.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

class Node {

int data;

Node next;

Node prev;

Node(int data) {

this.data = data;

this.next = this.prev = null;

public class CircularDoublyLinkedList {

Node head = null;

int size = 0;
// Insert at given index

public void insertAtIndex(int data, int index) {

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

System.out.println("Invalid index!");

return;

Node newNode = new Node(data);

if (head == null) {

head = newNode;

newNode.next = newNode.prev = newNode;

} else if (index == 0) {

Node tail = head.prev;

newNode.next = head;

newNode.prev = tail;

head.prev = newNode;

tail.next = newNode;

head = newNode;

} else {

Node temp = head;

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

temp = temp.next;

}
newNode.next = temp.next;

newNode.prev = temp;

temp.next.prev = newNode;

temp.next = newNode;

size++;

// Delete at given index

public void deleteAtIndex(int index) {

if (head == null || index < 0 || index >= size) {

System.out.println("Invalid index or empty list!");

return;

if (size == 1) {

head = null;

} else if (index == 0) {

Node tail = head.prev;

head = head.next;

head.prev = tail;

tail.next = head;

} else {

Node temp = head;

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


temp = temp.next;

temp.prev.next = temp.next;

temp.next.prev = temp.prev;

size--;

// Display forward from index

public void displayForwardFrom(int index) {

if (head == null || index < 0 || index >= size) {

System.out.println("Invalid index or list is empty!");

return;

Node temp = head;

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

temp = temp.next;

Node start = temp;

System.out.print("Forward from index " + index + ": ");

do {

System.out.print(temp.data + " ⇄ ");

temp = temp.next;
} while (temp != start);

System.out.println("(back to start)");

// Display backward from index

public void displayBackwardFrom(int index) {

if (head == null || index < 0 || index >= size) {

System.out.println("Invalid index or list is empty!");

return;

Node temp = head;

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

temp = temp.next;

Node start = temp;

System.out.print("Backward from index " + index + ": ");

do {

System.out.print(temp.data + " ⇄ ");

temp = temp.prev;

} while (temp != start);

System.out.println("(back to start)");

public static void main(String[] args) throws IOException {


CircularDoublyLinkedList list = new CircularDoublyLinkedList();

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

while (true) {

System.out.println("\n--- Circular Doubly Linked List ---");

System.out.println("1. Insert at Index");

System.out.println("2. Delete at Index");

System.out.println("3. Display Forward from Index");

System.out.println("4. Display Backward from Index");

System.out.println("5. Exit");

System.out.print("Enter your choice: ");

int choice = Integer.parseInt(br.readLine());

switch (choice) {

case 1:

System.out.print("Enter value: ");

int val = Integer.parseInt(br.readLine());

System.out.print("Enter index to insert: ");

int idx = Integer.parseInt(br.readLine());

list.insertAtIndex(val, idx);

break;

case 2:

System.out.print("Enter index to delete: ");

int delIdx = Integer.parseInt(br.readLine());

list.deleteAtIndex(delIdx);
break;

case 3:

System.out.print("Enter index to start forward display: ");

int fIndex = Integer.parseInt(br.readLine());

list.displayForwardFrom(fIndex);

break;

case 4:

System.out.print("Enter index to start backward display: ");

int bIndex = Integer.parseInt(br.readLine());

list.displayBackwardFrom(bIndex);

break;

case 5:

System.out.println("Exiting...");

return;

default:

System.out.println("Invalid choice!");

OUTPUT:
RESULT:

Thus, the Linked List implementations, including Singly, Doubly, Circular Singly,
and Circular Doubly Linked Lists, were successfully developed and tested. All core
operations such as insertion, deletion, searching, updating, and traversal were performed
accurately without any errors.

Exp. no: Sorting Algorithms

a) Bubble Sort

AIM:
To implement the Bubble Sort algorithm in Java to sort an array of integers in ascending
order.

ALGORITHM:

Step 1: Start the program.

Step 2: Read number of rows n and columns m.

Step 3: Create 2D array values[n][m].

Step 4: Initialize count = 0.

Step 5: For each element:

1. If even → increment count.

2. If odd → replace with -1.

Step 6: Create 1D array values1[count].

Step 7: Copy even numbers from 2D array into 1D array.

Step 8: Print:

3. All even numbers,  Total even count,

4. Modified 2D array.

Step 9: End the program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.util.Arrays;

public class bubble {

public static void main(String[] args) throws Exception {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));


System.out.println("enter size");

int size = Integer.parseInt(br.readLine());

int[] arr = new int[size];

System.out.println("enter " + size + " elements");

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

arr[i] = Integer.parseInt(br.readLine());

boolean swap;

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

swap = false;

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

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

int t = arr[j];

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

arr[j + 1] = t;

swap = true;

if (!swap) break;

System.out.println(Arrays.toString(arr));

}
OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of Sorting techniques
have been successfully executed

b) Insertion Sort

AIM:

To sort an array using Insertion Sort algorithm.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the array elements.

Step 3: For each element from index 1 to n-1:

 Store the element as key.

 Compare key with elements before it.

 Shift elements greater than key one position ahead.

 Insert key at correct position.

Step 4: Repeat till array is sorted.


Step 5: Display the sorted array.

Step 6: End the program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.util.Arrays;

public class InsertionSort {

public static void main(String[] args) throws Exception {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.print("Enter size: ");

int size = Integer.parseInt(br.readLine());

int[] arr = new int[size];

System.out.println("Enter " + size + " elements:");

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

arr[i] = Integer.parseInt(br.readLine());

for (int i = 1; i < size; 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;

System.out.println("Sorted Array: " + Arrays.toString(arr));

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of Sorting techniques
have been successfully executed

c) Selection Sort

AIM:

To sort an array using Selection Sort algorithm.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the array elements.


Step 3: For each element from index 0 to n-2:

o Assume the current index as min. o Compare with every other element after it.
o If any smaller element is found, update min.

o Swap the current element with the element at min.

Step 4: Repeat until the array is fully sorted.

Step 5: Display the sorted array.

Step 6: End the program.

SOURCE CODE:

import java.io.Bu eredReader

import java.io.InputStreamReader;

import java.util.Arrays;

public class selection {

public static void main(String[] args) throws Exception {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.println("Enter size:");

int size = Integer.parseInt(br.readLine());

int arr[] = new int[size];

System.out.println("Enter " + size + " elements:");

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

arr[i] = Integer.parseInt(br.readLine());

}
for (int i = 0; i < size - 1; i++) {

int min = i;

for (int j = i + 1; j < size; j++) {

if (arr[min] > arr[j]) {

min = j;

int t = arr[min];

arr[min] = arr[i];

arr[i] = t;

System.out.println("Sorted array: " + Arrays.toString(arr));

OUTPUT:

RESULT:
Thus all the JAVA programs to practice the implementation and usage of Sorting techniques
have been successfully executed

d) Merge Sort

AIM:

To sort an array using the Merge Sort algorithm.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the array elements.

Step 3: Divide the array into two halves recursively until each subarray has one element.

Step 4: Merge the sorted subarrays into a single sorted array:

o Create two temporary arrays to hold the divided halves.

o Compare elements and insert them in sorted order back into the main array.

Step 5: Repeat merging until the entire array is sorted.

Step 6: Display the sorted array.

Step 7: End the program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.io.IOException;

public class merg {

public static void main(String[] args) throws IOException {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in))


System.out.print("Enter number of elements: ");

int n = Integer.parseInt(br.readLine());

int[] array = new int[n];

System.out.println("Enter " + n + " integers :");

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

array[i] = Integer.parseInt(br.readLine());

System.out.println("Original array:");

printArray(array);

mergeSort(array, 0, array.length - 1);

System.out.println("Sorted array:");

printArray(array);

public static void mergeSort(int[] arr, int left, int right) {

if (left < right) {

int middle = (left + right) / 2;

mergeSort(arr, left, middle);

mergeSort(arr, middle + 1, right);

merge(arr, left, middle, right);

public static void merge(int[] arr, int left, int middle, int right) {
int n1 = middle - left + 1;

int n2 = right - middle;

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[middle + 1 + j];

int i = 0, j = 0, k = left;

while (i < n1 && j < n2) {

if (L[i] <= R[j]) {

arr[k++] = L[i++];

} else {

arr[k++] = R[j++];

while (i < n1)

arr[k++] = L[i++];

while (j < n2)

arr[k++] = R[j++];

}
public static void printArray(int[] arr) {

for (int value : arr)

System.out.print(value + " ");

System.out.println();

OUTPUT:

RESULT:

Thus all the JAVA programs to practice the implementation and usage of Sorting
techniques have been successfully executed

e) Quick Sort

AIM:

To sort an array using the Quick Sort algorithm.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the array elements.


Step 3: Choose the first element as the pivot.

Step 4: Initialize two pointers, i (start+1) and j (end).

Step 5: Move i to the right until an element greater than pivot is found.

Step 6: Move j to the left until an element smaller than or equal to pivot is found.

Step 7: If i < j, swap elements at i and j.

Step 8: After the loop, swap pivot with element at j.

Step 9: Recursively apply Quick Sort on subarrays to the left and right of pivot.

Step 10: Display the sorted array.

Step 11: End the program.

SOURCE CODE:

import java.io.Bu eredReader;

import java.io.InputStreamReader;

import java.util.Arrays;

public class quick {

public static void quicksort(int[] arr, int left, int right) {

if (left >= right) return;

int pivot = partition(arr, left, right);

quicksort(arr, left, pivot - 1);

quicksort(arr, pivot + 1, right);

private static int partition(int[] arr, int left, int right) {

int pivot = arr[left], i = left + 1, j = right;

while (i <= j) {
while (i <= j && arr[i] <= pivot) i++;

while (i <= j && arr[j] > pivot) j--;

if (i < j) swap(arr, i, j);

swap(arr, left, j);

return j;

private static void swap(int[] arr, int i, int j) {

int tem = arr[i];

arr[i] = arr[j];

arr[j] = tem;

public static void main(String[] args) throws Exception {

Bu eredReader br = new Bu eredReader(new InputStreamReader(System.in));

System.out.print("Enter size: ");

int size = Integer.parseInt(br.readLine());

int[] arr = new int[size];

System.out.println("Enter the elements:");

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

arr[i] = Integer.parseInt(br.readLine());

}
quicksort(arr, 0, size - 1);

System.out.println("Sorted Array: " + Arrays.toString(arr));

OUTPUT:

RESULT:

Thus, all sorting algorithms Bubble Sort, Insertion Sort, Selection Sort, Merge
Sort, and Quick Sort were successfully implemented. Each algorithm correctly sorted the
array elements in ascending order and displayed the sorted results without any errors.

Exp. no: Working with Linked list

a) Swapping the nodes of linked list


Aim:

To write a java programe to swap the pair of nodes in the linked list

Algoritham :

Step 1: Create a dummy node and set dummy.next = head.

Step 2: Initialize a pointer prev to point to the dummy node.

Step 3: Start a loop while head != null and head.next != null.

Step 4: Inside the loop:

Assign first = head and second = head.next.

Update links to swap:

o Set prev.next = second.

o Set first.next = second.next.

o Set second.next = first.

Step 5: Move prev pointer to first.

Step 6: Move head pointer to first.next.

Step 7: After the loop ends, update head = dummy.next (new head of the list).

SOURCE CODE:

class Node {

int data;

Node next;

public Node(int data) {

this.data = data;

this.next = null;

}
public class SwapPairsInLinkedList {

Node head;

public void swapPairs() {

if (head == null || head.next == null) {

return;

Node dummy = new Node(0);

dummy.next = head;

Node prev = dummy;

while (head != null && head.next != null) {

Node first = head;

Node second = head.next;

prev.next = second;

first.next = second.next;

second.next = first;

prev = first;

head = first.next;

head = dummy.next;
}

public void insertLast(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;

return;

Node temp = head;

while (temp.next != null) {

temp = temp.next;

temp.next = newNode;

public void display() {

Node temp = head;

while (temp != null) {

System.out.print(temp.data + " -> ");

temp = temp.next;

System.out.println("NULL");

public static void main(String[] args) {

SwapPairsInLinkedList list = new SwapPairsInLinkedList();


list.insertLast(1);

list.insertLast(2);

list.insertLast(3);

list.insertLast(4);

System.out.println("Original List:");

list.display();

list.swapPairs();

System.out.println("List after swapping pairs:");

list.display();

}}

Output:

Result:

 Pairs of nodes are swapped.

 If there’s an odd node at the end (in other examples), it stays in its place.

b) Reverse the linked list without any change in the head and tail.

Aim:
Reversing the linked list without changing the head and tail nodes.

Algoritham:

 Step-1(Check edge cases): If the list has less than 3 nodes, do nothing.

 Step-2(Identify key nodes) : Set prev = null, current = head.next, and tail = head.
Move tail to the last node.

 Step-3(Reverse the middle part) : While current.next != tail:

 Step-4: Store nextNode = current.next.

 Step-5: Reverse current.next = prev.

 Step-6: Move prev to current and current to nextNode.

 Step-7(Finish the reversal): Set current.next = prev.


Update head.next = current.

Source Code:

class Node {

int data;

Node next;

public Node(int data) {

this.data = data;

this.next = null;

public class ReverseExceptHeadTail {

Node head;
// Function to insert at end

public void insertLast(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;

return;

Node temp = head;

while (temp.next != null) {

temp = temp.next;

temp.next = newNode;

public void reverseExceptHeadTail() {

if (head == null || head.next == null || head.next.next == null) {

// Less than 3 nodes - nothing to reverse

return;

Node prev = null;

Node current = head.next;

Node tail = head;

while (tail.next != null) {

tail = tail.next;
}

Node last = tail;

while (current.next != last) {

Node nextNode = current.next;

current.next = prev;

prev = current;

current = nextNode;

current.next = prev;

head.next = current;

public void display() {

Node temp = head;

while (temp != null) {

System.out.print(temp.data + " -> ");

temp = temp.next;

System.out.println("NULL");

public static void main(String[] args) {

ReverseExceptHeadTail list = new ReverseExceptHeadTail();


list.insertLast(1);

list.insertLast(2);

list.insertLast(3);

list.insertLast(4);

list.insertLast(5);

System.out.println("Original List:");

list.display();

list.reverseExceptHeadTail();

System.out.println("List after reversing except head and tail:");

list.display();

Output:

Result:
 The first node (1) and last node (5) remain unchanged.

 The nodes between them (2, 3, 4) are reversed.

Exp. no: Working with both arrays and linked list

a) Rearrenge the Student name based on the roll.no

Aim:

Rearranging the student names in the linked list based on the roll.no in the array.

Algorithm:

 Step-1(Initialize): Create an array rollNumbers[] for roll numbers and a linked list for
names.

 Step-2(Display): Show the list before sorting.

 Step-3(Sort): Use Bubble Sort to sort rollNumbers[] and swap names in parallel.

 Step-4(Rebuild List): Clear the current list and insert names back in sorted order.

 Step-5(Display): Show the list after sorting.

SOURCE CODE:

class Node {

String name;

Node next;

public Node(String name) {

this.name = name;

this.next = null;
}

public class StudentListSorter {

Node head;

int[] rollNumbers;

public StudentListSorter(int[] rolls) {

this.rollNumbers = rolls;

public void insertLast(String name) {

Node newNode = new Node(name);

if (head == null) {

head = newNode;

return;

Node temp = head;

while (temp.next != null) {

temp = temp.next;

temp.next = newNode;

public void display() {


Node temp = head;

for (int roll : rollNumbers) {

if (temp != null) {

System.out.println("Roll No: " + roll + ", Name: " + temp.name);

temp = temp.next;

public void rearrange() {

int n = rollNumbers.length;

if (n <= 1 || head == null) return;

String[] names = new String[n];

Node temp = head;

int idx = 0;

while (temp != null) {

names[idx++] = temp.name;

temp = temp.next;

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

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

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

// Swap roll numbers

int tempRoll = rollNumbers[j];


rollNumbers[j] = rollNumbers[j + 1];

rollNumbers[j + 1] = tempRoll;

String tempName = names[j];

names[j] = names[j + 1];

names[j + 1] = tempName;

head = null; // Clear existing list

for (String name : names) {

insertLast(name);

public static void main(String[] args) {

int[] rolls = {2, 0, 3, 1};

StudentListSorter list = new StudentListSorter(rolls);

list.insertLast("ab");

list.insertLast("bc");

list.insertLast("cd");

list.insertLast("de");

System.out.println("Before Sorting:");
list.display();

list.rearrange();

System.out.println("\nAfter Sorting by Roll Numbers:");

list.display();

Output:

Result:
 The list is sorted by roll numbers, and the corresponding names are reordered to
match the sorted roll numbers.

 The final output will show the roll numbers and names in ascending order of roll
numbers.

You might also like