Skip to content

Commit b55f459

Browse files
Added Insertion Sort in java
1 parent d940c16 commit b55f459

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Sorting Algorithms/InsertionSort.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.Scanner;
2+
3+
public class InsertionSort
4+
{
5+
static void insertionSort(int arr[], int n)
6+
{
7+
int i,j,temp;
8+
for(i=0;i<n;i++)
9+
{
10+
temp = arr[i];
11+
j = i-1;
12+
while(j >=0 && arr[j] > temp)
13+
{
14+
arr[j+1] = arr[j];
15+
j--;
16+
}
17+
arr[j+1] = temp;
18+
}
19+
}
20+
public static void main(String[] args)
21+
{
22+
int size,i;
23+
System.out.println("Enter the size of the array : ");
24+
Scanner sc = new Scanner(System.in);
25+
size = sc.nextInt();
26+
int arr[] = new int[size];
27+
System.out.println("\nEnter "+size+" elements : ");
28+
for(i=0;i<size;i++)
29+
{
30+
arr[i] = sc.nextInt();
31+
}
32+
System.out.println("\nBefore sorting : ");
33+
for(i=0;i<size;i++)
34+
{
35+
System.out.print(arr[i]+" ");
36+
}
37+
insertionSort(arr,size);
38+
System.out.println("\nAfter sorting : ");
39+
for(i=0;i<size;i++)
40+
{
41+
System.out.print(arr[i]+" ");
42+
}
43+
44+
}
45+
}
46+
47+
48+
49+

0 commit comments

Comments
 (0)