-
Notifications
You must be signed in to change notification settings - Fork 110
/
solution.java
50 lines (43 loc) · 1.19 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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
// insertIntoSorted function
public static void insertIntoSorted(int[] arr) {
int pointer = arr[arr.length-1];
for(int i = arr.length-2; i >=0; i--){
if(pointer >= arr[i]){ // Found where it goes
arr[i+1] = pointer;
printArray(arr);
break;
}
arr[i+1] = arr[i]; // Shift to the right
printArray(arr);
}
if(pointer < arr[0]){
arr[0] = pointer;
printArray(arr);
}
}
// main function
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i]=in.nextInt();
}
insertIntoSorted(arr);
}
// print the array function
private static void printArray(int[] arr) {
for(int val: arr){
System.out.print(val+" ");
}
System.out.println("");
}
}
//Time Complexity: O(n)
//Space Complexity: O(1)