File tree 1 file changed +48
-0
lines changed
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Q: Write a java program to sort the array using selection sort algorithm.
2
+
3
+ import java .util .Scanner ;
4
+
5
+ public class SelectionSortAlgo {
6
+
7
+ public static void main (String [] args ) {
8
+ Scanner scan = new Scanner (System .in );
9
+ System .out .println ("Enter the array length:" );
10
+ int len = scan .nextInt ();
11
+ // Creating the array
12
+ int arr [] = new int [len ];
13
+ // Taking array elements from the user
14
+ System .out .println ("Enter array elements" );
15
+ for (int i = 0 ; i <= arr .length -1 ; i ++) {
16
+ System .out .println ("Enter an element:" );
17
+ arr [i ] = scan .nextInt ();
18
+ }
19
+ // Display array elements before sorting
20
+ System .out .println ("Array elements before sorting:" );
21
+ for (int i = 0 ; i <= arr .length -1 ; i ++) {
22
+ System .out .print (arr [i ] + " " );
23
+ }
24
+
25
+ // Selection sort logic
26
+ int min , pos , temp ;
27
+ for (int i = 0 ; i <= arr .length -2 ; i ++) {
28
+ min = arr [i ];
29
+ pos = i ;
30
+ for (int j = i +1 ; j <= arr .length -1 ; j ++) {
31
+ if (arr [j ] < min ) {
32
+ min = arr [j ];
33
+ pos = j ;
34
+ }
35
+ }
36
+ temp = arr [i ];
37
+ arr [i ] = arr [pos ];
38
+ arr [pos ] = temp ;
39
+ }
40
+
41
+ // Display array elements after sorting
42
+ System .out .println ();
43
+ System .out .println ("Array elements after sorting:" );
44
+ for (int i = 0 ; i <= arr .length -1 ; i ++) {
45
+ System .out .print (arr [i ] + " " );
46
+ }
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments