-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSortP1.java
56 lines (49 loc) · 1.12 KB
/
InsertionSortP1.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
55
56
import java.util.*;
public class InsertionSortP1
{
public static void insertIntoSorted(int[] arr)
{
int numToInsert = arr[arr.length-1];
int pos = arr.length-2;
while(pos>=0)
{
if(arr[pos]>numToInsert)
{
arr[pos+1]=arr[pos];
pos--;
printarray(arr);
}
else
{
arr[pos+1]=numToInsert;
printarray(arr);
break;
}
}
if(pos == -1)
{
arr[0]=numToInsert;
printarray(arr);
}
}
/* Tail starts here */
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] arr = new int[s];
for(int i=0;i<s;i++)
{
arr[i]=in.nextInt();
}
insertIntoSorted(arr);
}
private static void printarray(int[] arr)
{
for(int n: arr)
{
System.out.print(n+" ");
}
System.out.println("");
}
}