forked from AdarshAddee/Hacktoberfest2022_for_Beginers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.java
38 lines (36 loc) 路 971 Bytes
/
InsertionSort.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
/*Tharindu Sooriyaarachchi - https://github.com/TharinduDilshan */
public class InsertionSort
{
void insert(int a[])
{
int i, j, temp;
int n = a.length;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j])
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[])
{
int i;
int n = a.length;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
public static void main(String[] args) {
int a[] = { 92, 50, 5, 20, 11, 22 };
InsertionSort i1 = new InsertionSort();
System.out.println("\nBefore sorting array elements are - ");
i1.printArr(a);
i1.insert(a);
System.out.println("\n\nAfter sorting array elements are - ");
i1.printArr(a);
System.out.println();
}
}