-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion_Sort.java
More file actions
57 lines (51 loc) · 1.25 KB
/
Insertion_Sort.java
File metadata and controls
57 lines (51 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package matrix;
import java.util.*;
public class Insertion_Sort
{
public static Scanner ss=new Scanner(System.in);
public static Random rr=new Random();
//method to print the elements in the array
public static void print(int arr[])
{
for(int i=0;i<arr.length-1;i++)
{
System.out.print(arr[i]+",");
}
System.out.print(arr[arr.length-1]);
System.out.println();
}
/*
** is just like playing cards game
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before.
Move the greater elements one position up to make space for the swapped element.
Time Complexity: O(n*2)
*/
public static void insertionsort(int arr[])
{
for(int i=1;i<arr.length;i++)
{
int j=i-1;
int key=arr[i];
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
print(arr);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int n=ss.nextInt();
int arr[]=new int[n];
for(int j=0;j<arr.length;j++)
{
arr[j]=rr.nextInt(100);
}
print(arr);
insertionsort(arr);
}
}