Selection sort pick the first element from the array and scan whole array to find minimum
then swap with minimum, this happened one by one with each element in the array
complexity is = O(n^2)
public class SelectionSort {
public static void main(String[] args) {
int[] arr = { 2, 4, 23, 54, 67, 23, 66, 35, 28, 9, 65, 876, 32,1,0,2,4,5 };
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(selectionSort((arr))));
}
private static int[] selectionSort(int[] arr) {
for(int i=0;i<arr.length-1;i++) {
int minIndex = i;
for(int j = i+1;j<arr.length;j++) {
if(arr[j]<arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
}
then swap with minimum, this happened one by one with each element in the array
complexity is = O(n^2)
public class SelectionSort {
public static void main(String[] args) {
int[] arr = { 2, 4, 23, 54, 67, 23, 66, 35, 28, 9, 65, 876, 32,1,0,2,4,5 };
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(selectionSort((arr))));
}
private static int[] selectionSort(int[] arr) {
for(int i=0;i<arr.length-1;i++) {
int minIndex = i;
for(int j = i+1;j<arr.length;j++) {
if(arr[j]<arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
}