-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.java
More file actions
36 lines (29 loc) · 871 Bytes
/
insertionSort.java
File metadata and controls
36 lines (29 loc) · 871 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
35
36
import java.util.Scanner;
public class insertionSort {
private static void sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = in.nextInt();
System.out.println("Enter the elements of the array: ");
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
sort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
in.close();
}
}