forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort
More file actions
42 lines (35 loc) · 1.15 KB
/
SelectionSort
File metadata and controls
42 lines (35 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class SelectionSort {
// Method to perform Selection Sort
public static void selectionSort(int[] arr) {
int n = arr.length;
// One by one move the boundary of the unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted portion
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Method to print the array
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(arr);
selectionSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}