A selection sort repeatedly finds the smallest value from the unsorted array and moves it to a sorted subarray at the beginning of the array. It is continuously finding the smallest value and then moves it to the beginning of the array. There are two subarrays, one is the part that is sorted, and the other one are the reaming values that are unsorted. This algorithm is easy to implement, but it is not very efficient.
public class SelectionSort {
public static void main (String [] args){
int []values = {3,1,9,5,6,2,2,7,8,11};
selectionSort(values);
}
public static void selectionSort (int values[ ]) {
int arrlen = values.length;
// checks every value but the last
for (int i = 0; i < arrlen - 1; i++) {
int smallest = i;
// checks the rest of the array after the previous smallest number
for (int j = i + 1; j < arrlen; j++) {
if (values[j] < values[smallest])
smallest = j;
}
//smallest number switches places with the current number
int temp = values[smallest];
values[smallest] = values[i];
values[i] = temp;
//prints the values of the array
for (int j =0; j < values.length; j++){
System.out.println(" "+ values[j]);
}
}
//prints out the sorted array
for (int i = 0 ;i< values.length; i++){
System.out.println("sorted array");
System.out.print(" "+values[i]);
}
}
}
1
3
9
5
6
2
2
7
8
11
1
2
9
5
6
3
2
7
8
11
1
2
2
5
6
3
9
7
8
11
1
2
2
3
6
5
9
7
8
11
1
2
2
3
5
6
9
7
8
11
1
2
2
3
5
6
9
7
8
11
1
2
2
3
5
6
7
9
8
11
1
2
2
3
5
6
7
8
9
11
1
2
2
3
5
6
7
8
9
11
sorted array
1sorted array
2sorted array
2sorted array
3sorted array
5sorted array
6sorted array
7sorted array
8sorted array
9sorted array
11
Process finished with exit code 0