-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
34 lines (30 loc) · 1.01 KB
/
Copy pathSelectionSort.java
File metadata and controls
34 lines (30 loc) · 1.01 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
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// Find the smallest element in the unsorted part
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the smallest element with the first element of the unsorted part
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] numbers = {64, 25, 12, 22, 11};
System.out.println("Original Array:");
for (int num : numbers) {
System.out.print(num + " ");
}
selectionSort(numbers);
System.out.println("\nSorted Array:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}