File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ public class SelectionSort {
4
+ public static void main (String [] args ) {
5
+ Scanner scan = new Scanner (System .in );
6
+ int n = scan .nextInt ();
7
+ int [] arr = new int [n ];
8
+ for (int i = 0 ; i < n ; i ++)
9
+ arr [i ] = scan .nextInt ();
10
+ selectionSort (arr );
11
+ System .out .println (Arrays .toString (arr ));
12
+ }
13
+
14
+ public static void selectionSort (int [] arr ) {
15
+ for (int i = 0 ; i < arr .length ; i ++) {
16
+ // find the max item in the remaining array and swap with the correct index
17
+ int last = arr .length - i - 1 ;
18
+ int maxIndex = getMaxIndex (arr , 0 , last );
19
+ swap (arr , maxIndex , last );
20
+ }
21
+ }
22
+
23
+ public static int getMaxIndex (int [] arr , int start , int end ) {
24
+ int max = start ;
25
+ for (int i = start ; i <= end ; i ++) {
26
+ if (arr [i ] > arr [max ])
27
+ max = i ;
28
+ }
29
+ return max ;
30
+ }
31
+
32
+ public static void swap (int [] arr , int i , int correct ) {
33
+ int temp = arr [i ];
34
+ arr [i ] = arr [correct ];
35
+ arr [correct ] = temp ;
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments