Skip to content

Commit f55f3d3

Browse files
authored
Selection Sort in Java
1 parent 6fddfba commit f55f3d3

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.Arrays;
2+
/**
3+
* The selection sort algorithm chooses the smallest element from the array and
4+
* puts it in the first position. Then chooses the second smallest element and
5+
* stores it in the second position, and so on until the array is sorted.
6+
*/
7+
public class SelectionSort1{
8+
public static void selectionSort(int[] array, int leftIndex, int rightIndex) {
9+
for(int i = leftIndex; i <= rightIndex;i++) {
10+
int less = i;
11+
for(int j = i+1; j<= rightIndex; j++) {
12+
if(array[less] > array[j]) {
13+
less = j;
14+
}
15+
}
16+
int aux= array[i];
17+
array[i] = array[less];
18+
array[less] = aux;
19+
}
20+
}
21+
22+
/**
23+
* Main Method
24+
*/
25+
public static void main(String[] args) {
26+
int[] array = new int[] {8,1,4,5,7,2,3};
27+
selectionSort(array,0,array.length-1);
28+
System.out.println(Arrays.toString(array));
29+
30+
31+
}
32+
}

0 commit comments

Comments
 (0)