-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectionSort.java
44 lines (34 loc) · 1.52 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
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
// Find the minimum element in the unsorted part of the array
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[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
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("\nSorted Array:");
printArray(arr);
}
public static void printArray(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
/*The selection sort algorithm is a simple comparison-based sorting technique. It divides the input array into two parts: the sorted and unsorted portions. In each iteration, it finds the minimum element from the unsorted part and swaps it with the first element in the unsorted portion. This process continues until the entire array is sorted. Selection sort has a time complexity of O(n^2) and is not very efficient for large datasets but is easy to understand and implement.*/