-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort.java
60 lines (46 loc) · 930 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//insertion sort
//time complexity: O(2n) time even if the array is sorted.
import java.util.Scanner;
class InsertionSort
{
public void sort(int arr[])
{
int i,j,key;
int n=arr.length;
for(i=0;i<n;i++)
{
key = arr[i];
j = i-1;
while(j >=0 && arr[j] > key)
{
arr[j+1]= arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
public void print(int arr[])
{
int n = arr.length;
for(int i =0;i<n;i++)
{
System.out.print(" "+arr[i]+" ");
}
}
public static void main(String arg[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of an array:");
int size = scan.nextInt();
int [] arr = new int[size];
System.out.println("Enter the elements of an array:");
for(int i=0;i<size;i++)
{
arr[i] = scan.nextInt();
}
InsertionSort is = new InsertionSort();
is.sort(arr);
System.out.println("sorted array:");
is.print(arr);
}
}