File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Java Code to illustate Insertion sorting
2
+
3
+ import java .util .*;
4
+ import java .io .*;
5
+
6
+ public class InsertionSort {
7
+
8
+ public static void main (String args []){
9
+ //Declarartion of required variables
10
+ int size ;
11
+ Scanner sc =new Scanner (System .in );
12
+ //Reading Input
13
+ System .out .println ("Input :\n " );
14
+ System .out .println ("Enter the size of an array : \n " );
15
+ size =sc .nextInt ();
16
+ sc .nextLine ();
17
+ int arr []=new int [size ];
18
+ System .out .println ("Enter the elements of an array :\n " );
19
+ for (int index = 0 ; index < size ; index ++) {
20
+ arr [index ]=sc .nextInt ();
21
+ }
22
+ for (int index =1 ; index < size ; index ++) {
23
+ int temp =arr [index ];
24
+ int j =index -1 ;
25
+ while (j >=0 && arr [j ] > temp ) {
26
+ //Swapping the elements, temp is used to store the temporary variable
27
+ arr [j + 1 ] = arr [j ];
28
+ j =j -1 ;
29
+ }
30
+ arr [j +1 ]=temp ;
31
+ }
32
+ //Displaying Output
33
+ System .out .println ("Output :\n " );
34
+ System .out .println ("The sorted array is :\n " );
35
+ for (int index = 0 ; index < size ; index ++) {
36
+ System .out .print (arr [index ]+" " );
37
+ }
38
+
39
+ }
40
+ }
41
+
42
+ /*
43
+ Input:
44
+ Enter the size of an array: 4
45
+ Enter the elements of an array :
46
+ 10 8 1 4
47
+ Output :
48
+ 1 4 8 10
49
+ Time Complexity :O(n^2)
50
+ Space Complexity :O(1)
51
+ */
You can’t perform that action at this time.
0 commit comments