-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInsertionSortADT.java
50 lines (40 loc) · 1.02 KB
/
InsertionSortADT.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.util.Scanner;
public class InsertionSortADT
{
public static void main(String args[])
{
int a[]; // array reference
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
int n = sc.nextInt();
a = new int[n+1]; // dynamic memory allocation in java for array
System.out.println("Enter the array elements");
for(int i=1;i<=n;i++)
a[i] = sc.nextInt();
System.out.println("\n Before sorting...");
display(a,n);
insertionSort(a,n); // calling sorting function
System.out.println("\n After sorting...");
display(a,n);
}
public static void insertionSort(int a[], int n)
{
int i, j, temp;
for(i=1;i<=n;i++)
{
temp = a[i];
j = i-1; // j refers to previous positions
while((j>0) && (temp < a[j]))
{
a[j+1] = a[j]; // a[i-1+1] = a[i-1]
j--;
} // shifting is finished
a[j+1] = temp; // Placing the temp back in the empty position
}
}
public static void display(int a[],int n)
{
for(int i=1;i<=n;i++)
System.out.print(a[i]+" ");
}
}