-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInsertionSort2.java
More file actions
52 lines (40 loc) · 1.06 KB
/
InsertionSort2.java
File metadata and controls
52 lines (40 loc) · 1.06 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
// https://www.hackerrank.com/challenges/insertionsort2
/*
Time Complexity - O(n^2)
Space Complexity - O(1)
Test Case 1
6
1 4 3 5 6 2
*/
import java.util.Scanner;
class InsertionSort2 {
public static void insertionSortPart2(int[] ar)
{
int len = ar.length;
for(int i = 1; i < len; i++) {
int key = ar[i];
int j = i - 1;
while(j >=0 && key < ar[j]) {
ar[j+1] = ar[j];
j--;
}
ar[j+1] = key;
printArray(ar);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertionSortPart2(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}