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