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

Lab Manual - DSA

Practical lab file.

Uploaded by

devkirtani64
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lab Manual - DSA

Practical lab file.

Uploaded by

devkirtani64
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Name of Program: MCA

LAB MANUAL
Name Of Course Data Structures and Algorithms Lab

Course Code BCA357A

Semester III

Name of Faculty Sandhya Gautam

Academic Year 2024

School of Computer Applications


JECRC UNIVERSITY
Session 2024-25
Table of Contents

Contents Page No.

Objectives

Prerequisites, if Any

NA

Course Outcomes 3

Mapping Between Course Outcome and 4


Program Outcomes

Syllabus/List of Programs 5

Program Solutions with Outputs 6-43


Course Objectives :

1. To impart the basic concepts of data structures and algorithms

2. To define stacks, queues, lists, trees and graphs.

3. To implement the concepts about searching and sorting techniques.

4. To identify the algorithms and a step by step approach to solving problems.

5. To use algorithms to solve real world problems.

Course Outcomes:

CO 1 Explain the basic knowledge of data structure used in computer systems

CO 2 Define the Linear and Non-Linear Data Structures

CO 3 Implement the sorting and searching techniques for appropriate real-world problems

CO 4 Working on real world scenario with the backtracking algorithms

Apply the appropriate data structures, algorithms, and realizations to solve simple to
CO 5
complex real-world issues.
Mapping Between Course Outcome and Program Outcomes:

Course
Learning PO PSO PSO PSO
PO1 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Outcomes 2 1 2 3
(CLOs)

CO1 2 2 2 2 2 2 3 3 3 3 3 3

CO2 2 2 1 2 2 2 3 3 3 3 3 2 3 3

CO3 2 2 2 2 2 3 3 3 3 3 3

CO4 2 3 2 2 3 3 3 3 3 3 2 3

CO5 2 2 2 3 3 3 3 3 3 3 3 2 3

Syllabus/List of Programs:
1. Basic Program

1.1 Write a Java program that prints the following pattern: Hello, World!

2. Array

2.1 Write a program to store elements in an array and print them.

2.2 Write a program to find the sum of all array elements.

2.3 Write a program to merge two arrays of the same size sorted in descending
order.

3. String Manipulation

3.1 Perform basic string operations like concatenation and substring extraction in
Java.

3.2 Implement dynamic strings in Java and analyze their memory representation.

3.3 Implement a function to find all permutations of a string.

4. Stack & Queue Operations

4.1 Perform basic stack operations (push, pop, display) using arrays in Java.

4.2 Implement stack operations using linked lists in Java.

4.3 Implement queues using linked lists in Java.

5. Manipulate Linked Lists

5.1 Create and manipulate singly linked lists in Java.

5.2 Implement doubly linked lists in Java.

6. Tree Traversals and Binary Search Tree Operations

6.1 Write a Java program that converts an arithmetic expression from infix
notation to postfix notation.

6.2 Implement preorder, inorder, and postorder traversals in Java.

6.3 Create and perform basic operations on Binary Search Trees (BSTs) in Java.

7. Analyze Binary Trees with User Input

7.1 Write a program to create a binary tree where the user inputs the values for
each node. After building the tree, print the values in an in-order traversal.
7.2 Write a program to find the height of a binary tree. The user will input the
values for each node, and the program will calculate and display the height of the
tree.

7.3 Write a program to count the number of leaf nodes in a binary tree. The user
will provide the values for each node, and the program will count and display the
number of leaf nodes.

8. Searching Algorithms

8.1 Write a Java program that performs an unordered linear search. The program
should take an array of integers and a target integer as input, then determine
whether the target exists in the array and print the index if found.

8.2 Write a Java program that performs a sorted linear search. The program
should take a sorted array of integers and a target integer as input, then
determine whether the target exists in the array and print the index if found.

8.3 Write a Java program that performs a binary search on a sorted array using
recursion. The program should take a sorted array of integers and a target
integer as input, then determine whether the target exists in the array and print
the index if found.

9. Sorting Algorithms

9.1 Implement bubble sort in Java.

9.2 Implement insertion sort and analyze its performance in Java.

9.3 Implement selection sort and compare with other basic sorting algorithms in Java.
Practical 1.1 Write a Java program that prints the following pattern: Hello, World!

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

Practical 2.1 Write a program to store elements in an array and print them.

public class ArrayExample {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5};

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

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

Practical 2.2 Write a program to find the sum of all array elements.

public class ArraySum {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5};

int sum = 0;

for (int num : array) {

sum += num;

}
System.out.println("Sum of array elements: " + sum);

Practical 2.3 Write a program to merge two arrays of the same size sorted in descending
order.

import java.util.Arrays;

import java.util.Collections;

public class MergeArrays {

public static void main(String[] args) {

Integer[] array1 = {1, 3, 5};

Integer[] array2 = {2, 4, 6};

Integer[] mergedArray = new Integer[array1.length + array2.length];

System.arraycopy(array1, 0, mergedArray, 0, array1.length);

System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);

Arrays.sort(mergedArray, Collections.reverseOrder());

System.out.println("Merged Array in descending order: " + Arrays.toString(mergedArray));

Practical 3.1 Perform basic string operations like concatenation and substring extraction
in Java.

public class StringOperations {

public static void main(String[] args) {

String str1 = "Hello";


String str2 = "World";

// Concatenation

String concatenated = str1 + ", " + str2 + "!";

System.out.println("Concatenated String: " + concatenated);

// Substring extraction

String substring = concatenated.substring(0, 5);

System.out.println("Extracted Substring: " + substring);

Practical 3.2 Implement dynamic strings in Java and analyze their memory
representation.

public class DynamicString {

public static void main(String[] args) {

StringBuilder dynamicString = new StringBuilder("Hello");

dynamicString.append(" World!");

System.out.println("Dynamic String: " + dynamicString.toString());

Practical 3.3 Implement a function to find all permutations of a string.

public class StringPermutations {

public static void main(String[] args) {

String str = "ABC";

permute(str, "");

}
public static void permute(String str, String prefix) {

if (str.length() == 0) {

System.out.println(prefix);

} else {

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

permute(str.substring(0, i) + str.substring(i + 1), prefix + str.charAt(i));

Practical 4.1 Perform basic stack operations (push, pop, display) using arrays in Java.

class Stack {

private int maxSize;

private int top;

private int[] stackArray;

public Stack(int size) {

maxSize = size;

stackArray = new int[maxSize];

top = -1;

public void push(int value) {

if (top < maxSize - 1) {

stackArray[++top] = value;

} else {
System.out.println("Stack Overflow");

public int pop() {

return (top >= 0) ? stackArray[top--] : -1;

public void display() {

for (int i = top; i >= 0; i--) {

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

public class StackExample {

public static void main(String[] args) {

Stack stack = new Stack(5);

stack.push(1);

stack.push(2);

stack.push(3);

stack.display();

Practical 5.1 Create and manipulate singly linked lists in Java.

class Node {
int data;

Node next;

Node(int data) {

this.data = data;

this.next = null;

class LinkedList {

Node head;

public void add(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;

public void display() {


Node temp = head;

while (temp != null) {

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

temp = temp.next;

public class SinglyLinkedList {

public static void main(String[] args) {

LinkedList list = new LinkedList();

list.add(1);

list.add(2);

list.add(3);

list.display();

Practical 5.2 Implement Doubly Linked Lists in Java

class DoublyNode {

int data;

DoublyNode next;

DoublyNode prev;

DoublyNode(int data) {

this.data = data;

this.next = null;

this.prev = null;
}

class DoublyLinkedList {

DoublyNode head;

// Insert at the end

public void insert(int data) {

DoublyNode newNode = new DoublyNode(data);

if (head == null) {

head = newNode;

} else {

DoublyNode temp = head;

while (temp.next != null) {

temp = temp.next;

temp.next = newNode;

newNode.prev = temp;

// Display list forward

public void displayForward() {

DoublyNode temp = head;

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

while (temp != null) {


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

temp = temp.next;

System.out.println();

// Display list backward

public void displayBackward() {

DoublyNode temp = head;

if (temp == null) return;

while (temp.next != null) {

temp = temp.next;

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

while (temp != null) {

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

temp = temp.prev;

System.out.println();

public class DoublyLinkedListExample {

public static void main(String[] args) {


DoublyLinkedList dll = new DoublyLinkedList();

dll.insert(1);

dll.insert(2);

dll.insert(3);

dll.displayForward();

dll.displayBackward();

Practical 6.1 Convert Infix Expression to Postfix in Java

import java.util.Stack;

public class InfixToPostfix {

// Function to check operator precedence

static int precedence(char ch) {

switch (ch) {

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '^':

return 3;

return -1;

}
// Convert infix to postfix

public static String infixToPostfix(String expression) {

StringBuilder result = new StringBuilder();

Stack<Character> stack = new Stack<>();

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

char c = expression.charAt(i);

// If the character is an operand, add it to output

if (Character.isLetterOrDigit(c)) {

result.append(c);

// If the character is '(', push it to the stack

else if (c == '(') {

stack.push(c);

// If the character is ')', pop and output until '(' is found

else if (c == ')') {

while (!stack.isEmpty() && stack.peek() != '(') {

result.append(stack.pop());

stack.pop();

} else { // Operator encountered

while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) {

result.append(stack.pop());
}

stack.push(c);

// Pop all operators from the stack

while (!stack.isEmpty()) {

result.append(stack.pop());

return result.toString();

public static void main(String[] args) {

String expression = "A+B*(C^D-E)";

System.out.println("Infix Expression: " + expression);

System.out.println("Postfix Expression: " + infixToPostfix(expression));

Practical 6.2 Implement Preorder, Inorder, and Postorder Traversals in Java

class TreeNode {

int data;

TreeNode left, right;

TreeNode(int data) {

this.data = data;
left = right = null;

class BinaryTree {

TreeNode root;

// Preorder Traversal

public void preorder(TreeNode node) {

if (node == null) return;

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

preorder(node.left);

preorder(node.right);

// Inorder Traversal

public void inorder(TreeNode node) {

if (node == null) return;

inorder(node.left);

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

inorder(node.right);

// Postorder Traversal

public void postorder(TreeNode node) {

if (node == null) return;


postorder(node.left);

postorder(node.right);

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

public class TreeTraversalExample {

public static void main(String[] args) {

BinaryTree tree = new BinaryTree();

tree.root = new TreeNode(1);

tree.root.left = new TreeNode(2);

tree.root.right = new TreeNode(3);

tree.root.left.left = new TreeNode(4);

tree.root.left.right = new TreeNode(5);

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

tree.preorder(tree.root);

System.out.print("\nInorder: ");

tree.inorder(tree.root);

System.out.print("\nPostorder: ");

tree.postorder(tree.root);

Practical 6.3 Create and Perform Basic Operations on Binary Search Trees (BSTs) in Java

class BSTNode {

int key;
BSTNode left, right;

public BSTNode(int item) {

key = item;

left = right = null;

class BinarySearchTree {

BSTNode root;

BinarySearchTree() {

root = null;

// Insert a new key

void insert(int key) {

root = insertRec(root, key);

BSTNode insertRec(BSTNode root, int key) {

if (root == null) {

root = new BSTNode(key);

return root;

}
if (key < root.key) {

root.left = insertRec(root.left, key);

} else if (key > root.key) {

root.right = insertRec(root.right, key);

return root;

// Search for a key

boolean search(int key) {

return searchRec(root, key) != null;

BSTNode searchRec(BSTNode root, int key) {

if (root == null || root.key == key) {

return root;

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

// Delete a key

void delete(int key) {

root = deleteRec(root, key);

BSTNode deleteRec(BSTNode root, int key) {


if (root == null) return root;

if (key < root.key) {

root.left = deleteRec(root.left, key);

} else if (key > root.key) {

root.right = deleteRec(root.right, key);

} else {

if (root.left == null) return root.right;

if (root.right == null) return root.left;

root.key = minValue(root.right);

root.right = deleteRec(root.right, root.key);

return root;

int minValue(BSTNode root) {

int minValue = root.key;

while (root.left != null) {

root = root.left;

minValue = root.key;

return minValue;

}
// Inorder traversal

void inorder() {

inorderRec(root);

void inorderRec(BSTNode root) {

if (root != null) {

inorderRec(root.left);

System.out.print(root.key + " ");

inorderRec(root.right);

public class BSTExample {

public static void main(String[] args) {

BinarySearchTree bst = new BinarySearchTree();

bst.insert(50);

bst.insert(30);

bst.insert(20);

bst.insert(40);

bst.insert(70);

bst.insert(60);

bst.insert(80);

System.out.print("Inorder traversal: ");


bst.inorder();

System.out.println("\nSearching for 40: " + bst.search(40));

System.out.println("Deleting 20");

bst.delete(20);

System.out.print("Inorder traversal after deletion: ");

bst.inorder();

Practical 7.1 Create a Binary Tree and Perform In-Order Traversal

import java.util.Scanner;

class Node {

int data;

Node left, right;

Node(int data) {

this.data = data;

left = right = null;

class BinaryTree {

Node root;

// Insert node into the binary tree


public Node insert(Node root, int data) {

if (root == null) {

return new Node(data);

} else {

if (data < root.data) {

root.left = insert(root.left, data);

} else {

root.right = insert(root.right, data);

return root;

// In-order traversal

public void inOrderTraversal(Node root) {

if (root != null) {

inOrderTraversal(root.left);

System.out.print(root.data + " ");

inOrderTraversal(root.right);

public class BinaryTreeInOrder {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


BinaryTree tree = new BinaryTree();

System.out.println("Enter number of nodes:");

int n = scanner.nextInt();

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

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

int data = scanner.nextInt();

tree.root = tree.insert(tree.root, data);

System.out.print("In-order Traversal: ");

tree.inOrderTraversal(tree.root);

Practical 7.2 Calculate the Height of a Binary Tree

import java.util.Scanner;

class BinaryTreeHeight {

Node root;

// Method to calculate height of the binary tree

public int findHeight(Node node) {

if (node == null) {

return -1;

} else {
int leftHeight = findHeight(node.left);

int rightHeight = findHeight(node.right);

return Math.max(leftHeight, rightHeight) + 1;

public class BinaryTreeHeightCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

BinaryTreeHeight tree = new BinaryTreeHeight();

System.out.println("Enter number of nodes:");

int n = scanner.nextInt();

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

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

int data = scanner.nextInt();

tree.root = tree.insert(tree.root, data);

System.out.println("Height of the tree: " + tree.findHeight(tree.root));

Practical 7.3 Count Leaf Nodes in a Binary Tree

class BinaryTreeLeafCount {
Node root;

// Method to count leaf nodes

public int countLeaves(Node node) {

if (node == null) return 0;

if (node.left == null && node.right == null) return 1;

return countLeaves(node.left) + countLeaves(node.right);

public class LeafNodeCounter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

BinaryTreeLeafCount tree = new BinaryTreeLeafCount();

System.out.println("Enter number of nodes:");

int n = scanner.nextInt();

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

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

int data = scanner.nextInt();

tree.root = tree.insert(tree.root, data);

System.out.println("Number of leaf nodes: " + tree.countLeaves(tree.root));

}
}

Practical 8.1 Create an Undirected Graph Using an Adjacency Matrix

import java.util.Scanner;

public class GraphAdjacencyMatrix {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter number of vertices:");

int vertices = scanner.nextInt();

int[][] adjMatrix = new int[vertices][vertices];

System.out.println("Enter number of edges:");

int edges = scanner.nextInt();

System.out.println("Enter the edges (format: u v):");

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

int u = scanner.nextInt();

int v = scanner.nextInt();

adjMatrix[u][v] = 1;

adjMatrix[v][u] = 1; // For undirected graph

System.out.println("Adjacency Matrix:");

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


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

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

System.out.println();

Practical 8.2 Find Degree of a Vertex in an Undirected Graph

import java.util.Scanner;

public class GraphVertexDegree {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter number of vertices:");

int vertices = scanner.nextInt();

int[][] adjMatrix = new int[vertices][vertices];

System.out.println("Enter number of edges:");

int edges = scanner.nextInt();

System.out.println("Enter the edges (format: u v):");

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

int u = scanner.nextInt();

int v = scanner.nextInt();
adjMatrix[u][v] = 1;

adjMatrix[v][u] = 1; // For undirected graph

System.out.println("Enter the vertex to find its degree:");

int vertex = scanner.nextInt();

int degree = 0;

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

degree += adjMatrix[vertex][i];

System.out.println("Degree of vertex " + vertex + " is: " + degree);

Practical 8.3 Check if an Undirected Graph is Connected

import java.util.*;

public class GraphConnected {

private static Map<Integer, List<Integer>> graph;

private static boolean[] visited;

// Perform DFS to visit all reachable nodes

private static void dfs(int node) {

visited[node] = true;

for (int neighbor : graph.get(node)) {


if (!visited[neighbor]) {

dfs(neighbor);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter number of vertices:");

int vertices = scanner.nextInt();

graph = new HashMap<>();

visited = new boolean[vertices];

// Initialize the adjacency list

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

graph.put(i, new ArrayList<>());

System.out.println("Enter number of edges:");

int edges = scanner.nextInt();

System.out.println("Enter the edges (format: u v):");

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

int u = scanner.nextInt();
int v = scanner.nextInt();

graph.get(u).add(v);

graph.get(v).add(u); // Since the graph is undirected

// Perform DFS starting from vertex 0

dfs(0);

// Check if all vertices were visited

boolean isConnected = true;

for (boolean nodeVisited : visited) {

if (!nodeVisited) {

isConnected = false;

break;

if (isConnected) {

System.out.println("The graph is connected.");

} else {

System.out.println("The graph is not connected.");

Practical 9.1 Unordered Linear Search

import java.util.Scanner;
public class UnorderedLinearSearch {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

int[] arr = new int[n];

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

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

arr[i] = scanner.nextInt();

System.out.println("Enter the target value to search:");

int target = scanner.nextInt();

// Unordered linear search

int index = -1;

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

if (arr[i] == target) {

index = i;

break;

}
if (index != -1) {

System.out.println("Target found at index: " + index);

} else {

System.out.println("Target not found.");

Practical 9.2 Sorted Linear Search

import java.util.Scanner;

public class SortedLinearSearch {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

int[] arr = new int[n];

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

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

arr[i] = scanner.nextInt();

System.out.println("Enter the target value to search:");

int target = scanner.nextInt();


// Sorted linear search

int index = -1;

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

if (arr[i] == target) {

index = i;

break;

if (arr[i] > target) { // No need to search further in a sorted array

break;

if (index != -1) {

System.out.println("Target found at index: " + index);

} else {

System.out.println("Target not found.");

Practical 9.3 Binary Search using Recursion

import java.util.Scanner;

public class RecursiveBinarySearch {

// Recursive function for binary search


public static int binarySearch(int[] arr, int target, int left, int right) {

if (left > right) {

return -1;

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

if (arr[mid] == target) {

return mid;

if (arr[mid] > target) {

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

} else {

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

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

int[] arr = new int[n];

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


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

arr[i] = scanner.nextInt();

System.out.println("Enter the target value to search:");

int target = scanner.nextInt();

// Perform binary search using recursion

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

if (result != -1) {

System.out.println("Target found at index: " + result);

} else {

System.out.println("Target not found.");

Practical 10.1 Bubble Sort

import java.util.Scanner;

public class BubbleSort {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();
int[] arr = new int[n];

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

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

arr[i] = scanner.nextInt();

// Bubble sort algorithm

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

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

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

// Swap arr[j] and arr[j + 1]

int temp = arr[j];

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

arr[j + 1] = temp;

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

for (int num : arr) {

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

}
Practical 10.2 Insertion Sort

import java.util.Scanner;

public class InsertionSort {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

int[] arr = new int[n];

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

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

arr[i] = scanner.nextInt();

// Insertion sort algorithm

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

int key = arr[i];

int j = i - 1;

// Move elements of arr[0..i-1] that are greater than key

while (j >= 0 && arr[j] > key) {

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

j = j - 1;

}
arr[j + 1] = key;

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

for (int num : arr) {

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

Practical 10.3 Selection Sort

import java.util.Scanner;

public class SelectionSort {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

int[] arr = new int[n];

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

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

arr[i] = scanner.nextInt();

// Selection sort algorithm


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

int minIdx = i;

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

if (arr[j] < arr[minIdx]) {

minIdx = j;

// Swap the found minimum element with the first element

int temp = arr[minIdx];

arr[minIdx] = arr[i];

arr[i] = temp;

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

for (int num : arr) {

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

You might also like