Skip to content

Commit 29b193f

Browse files
Create 20.1 Insertion Sort.java
for(int i=1;i<n;i++) { int key = Z[i]; int j = i-1; while(j>=0) { if(key>Z[j]) { Z[j+1] = Z[j]; Z[j] = key; } j--; } }
1 parent 0d971ce commit 29b193f

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

20.1 Insertion Sort.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Akash is found of collecting unique coins. Every coin has a denomination i.e Z. One Afternoon, he has K coins. He wnat to arrange K coins in non-increaasing order as per denomination. Write a programming solution to help akash. - Note: Use Insertion Sort
3+
4+
Input Format
5+
6+
1st line contain K Coins
7+
2nd line contain space separated denomination from K coins
8+
Constraints
9+
10+
K>0 & K<50
11+
Z>0 & Z<100
12+
Output Format
13+
14+
space separated sorted denomination from K coins
15+
16+
Sample Input 0
17+
18+
5
19+
10 4 3 7 8
20+
Sample Output 0
21+
22+
10 8 7 4 3
23+
*/
24+
25+
import java.io.*;
26+
import java.util.*;
27+
import java.text.*;
28+
import java.math.*;
29+
import java.util.regex.*;
30+
31+
public class Solution {
32+
public static void main(String args[] ) throws Exception {
33+
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
34+
Scanner sc = new Scanner(System.in);
35+
//take input for number of coins: n
36+
int n = sc.nextInt();
37+
//take input for domination of each coin ie. Z as an array
38+
int [] Z = new int [n];
39+
for(int i=0;i<n;i++)
40+
Z[i] = sc.nextInt();
41+
42+
//for sorting we use INSERTION SORT
43+
44+
for(int i=1;i<n;i++)
45+
{
46+
int key = Z[i];
47+
int j = i-1;
48+
while(j>=0)
49+
{
50+
if(key>Z[j])
51+
{
52+
Z[j+1] = Z[j];
53+
Z[j] = key;
54+
}
55+
j--;
56+
}
57+
58+
}
59+
60+
//printing the final sorted array ie. Z
61+
62+
for(int i:Z)
63+
System.out.print(i+" ");
64+
}
65+
}

0 commit comments

Comments
 (0)