1public static void SelectionSort(int[] arr)
2{
3 int small;
4 for (int i = 0; i <arr.length - 1; i++)
5 {
6 small = i;
7 for (int j = i + 1; j < arr.length; j++)
8 {
9 //if current position is less than previous smallest
10 if (arr[j] < arr[small])
11 {
12 small = j;
13
14 //swap values
15 int temp = arr[i];
16 arr[i] = arr[small];
17 arr[small] = temp;
18 }
19 }
20 }
21}
1// example on selection sort java
2public class SelectionSortInJava
3{
4 void toSort(int[] arrNum)
5 {
6 int number = arrNum.length;
7 for(int a = 0; a < number - 1; a++)
8 {
9 // finding minimum element
10 int minimum = a;
11 for(int b = a + 1; b < number; b++)
12 {
13 if(arrNum[b] < arrNum[minimum])
14 {
15 minimum = b;
16 }
17 }
18 // swapping minimum element with first element
19 int temp = arrNum[minimum];
20 arrNum[minimum] = arrNum[a];
21 arrNum[a] = temp;
22 }
23 }
24 // printing array
25 void displayArray(int[] arrPrint)
26 {
27 int num = arrPrint.length;
28 for(int a = 0; a < num; ++a)
29 {
30 System.out.print(arrPrint[a] + " ");
31 }
32 System.out.println();
33 }
34 public static void main(String[] args)
35 {
36 SelectionSortInJava obj = new SelectionSortInJava();
37 int[] arrInput = {5, 4, -3, 2, -1};
38 obj.toSort(arrInput);
39 System.out.println("After sorting : ");
40 obj.displayArray(arrInput);
41 }
42}
1static void selectionSort(int[] arr) {
2 int lowest, lowestIndex;
3 for(int i = 0; i < arr.length -1; i++) {
4 //Find the lowest
5 lowest = arr[i];
6 lowestIndex = i;
7 for(int j = i; j < arr.length; j++) {
8 if(arr[j] < lowest) {
9 lowest = arr[j];
10 lowestIndex = j;
11 }
12 }
13 //Swap
14 if(i != lowestIndex) {
15 int temp = arr[i];
16 arr[i] = arr[lowestIndex];
17 arr[lowestIndex] = temp;
18 }
19
20 }
21 }