Skip to content

Commit 6a3d8fe

Browse files
committed
Added InsertionSort in Classic Java Algorithm
1 parent 9f9ce3f commit 6a3d8fe

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.Scanner;
2+
public class InsertionSort
3+
{
4+
private static void insertionSort(int array[], int size){
5+
for (int i = 1; i < size; i++){
6+
int key = array[i];
7+
int j = i -1;
8+
while ( j >= 0 && array[j] > key) {
9+
array[j+1] = array[j];
10+
j = j - 1;
11+
}
12+
array[j+1] = key;
13+
}
14+
}
15+
16+
private static void printArray(int array[]) {
17+
for(int i = 0; i < array.length;i++) {
18+
System.out.print(array[i] + " ");
19+
}
20+
System.out.println();
21+
}
22+
23+
public static void main(String[] args) {
24+
Scanner scan = new Scanner(System.in);
25+
try {
26+
int i,n;
27+
System.out.println("How many elements do you want in the array?");
28+
n=scan.nextInt();
29+
int a[]= new int[n];
30+
System.out.println("Enter the array elements one by one");
31+
32+
for(i=0;i<n;i++)
33+
{
34+
a[i]=scan.nextInt();
35+
}
36+
System.out.println("Array before sorting is:");
37+
printArray(a);
38+
System.out.println("Array before sorting is:");
39+
insertionSort(a, a.length);
40+
printArray(a);
41+
42+
} catch(Exception e) {e.printStackTrace();}
43+
scan.close();
44+
}
45+
}

0 commit comments

Comments
 (0)