-
Notifications
You must be signed in to change notification settings - Fork 53
/
SelectionSort.java
50 lines (39 loc) · 1.22 KB
/
SelectionSort.java
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
43
44
45
46
47
48
49
50
package Java_DSA.Problems.Arrays;
public class SelectionSort {
static void selectionSort(int[] arr){
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element
// is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
static void printArray(int[] arr){
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
public static void main(String[] args){
int[] arr = { 64, 25, 12, 22, 11 };
System.out.print("Original array: ");
printArray(arr);
selectionSort(arr);
System.out.print("Sorted array: ");
printArray(arr);
}
}