-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
42 lines (40 loc) · 1.2 KB
/
InsertionSort.java
File metadata and controls
42 lines (40 loc) · 1.2 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
import java.util.Scanner;
public class InsertionSort
{
public static void insertion( int a[] )
{
int i, b,t;
int len = a.length;
for (i = 1; i< len; i++)
{
b = i;
t = a[i];
while (b > 0 && t < a[b-1])
{
a[b] = a[b-1];
b = b-1;
}
a[b] = t;
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
int n;
System.out.println("Enter number the limit");
n = scan.nextInt();
int a[] = new int[ n ];
System.out.println("\nEnter the "+ n + " elements");
for (int i = 0; i < n; i++)
a[i] = scan.nextInt();
System.out.println("\nElements before sorting");
for (int i = 0; i < n; i++)
System.out.print(a[i]+" ");
System.out.println();
insertion(a);
System.out.println("\nElements after sorting");
for (int i = 0; i < n; i++)
System.out.print(a[i]+" ");
System.out.println();
}
}