-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInsertionsort.java
More file actions
34 lines (31 loc) · 877 Bytes
/
Insertionsort.java
File metadata and controls
34 lines (31 loc) · 877 Bytes
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
import java.util.Arrays;
import java.util.Scanner;
public class InsertionSort{
public static 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;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
System.out.print("Enter Size of Array:");
n = sc.nextInt();
int arr[] = new int[n];
System.out.print("Enter Array:");
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
sort(arr);
System.out.println("Sorted array");
System.out.println(Arrays.toString(arr));
}
}