-
Notifications
You must be signed in to change notification settings - Fork 693
/
Solution.java
54 lines (43 loc) · 1.17 KB
/
Solution.java
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
//Problem: https://www.hackerrank.com/challenges/insertionsort1
//Java 8
//Time Complexity: O(n)
//Space Complexity: O(1)
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void insertIntoSorted(int[] ar) {
int tmp = ar[ar.length-1];
for(int i = ar.length-2; i >=0; i--){
if(tmp >= ar[i]){//Found where it goes
ar[i+1] = tmp;
printArray(ar);
break;
}
ar[i+1] = ar[i];//Shift to the right
printArray(ar);
}
if(tmp < ar[0]){
ar[0] = tmp;
printArray(ar);
}
}
/* Tail starts here */
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();
}
insertIntoSorted(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}