forked from thisisshub/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion_sort
45 lines (42 loc) · 949 Bytes
/
Insertion_sort
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
import java.util.Scanner;
class Insertion_Sort
{
void sort(int arr[])
{
int n = arr.length;
for (int i=1; i<n; ++i)
{
int key = arr[i];
int j = i-1;
while (j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array Size");
int size=sc.nextInt();
int arr[] = new int[size];
System.out.println("Enter Array Elements");
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
Insertion_Sort obj = new Insertion_Sort();
obj.sort(arr);
System.out.println("Sorted array after using insertion sort:");
printArray(arr);
}
}