-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort.java
55 lines (38 loc) · 1.17 KB
/
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
import java.util.*;
class Firstclass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// take indexes
System.out.print("Enter number of indexes: ");
int n = sc.nextInt();
// create an array with n index
int arr[] = new int[n];
int num = 1;
// taking input from user
for(int i = 0; i < n; i += 1) {
System.out.print("Enter " + num + " index: ");
arr[i] = sc.nextInt();
num += 1;
}
System.out.print("Unsorted array: \n");
for(int i = 0; i < n; i += 1) {
System.out.print(arr[i] + " ");
}
System.out.print("\n");
// sorting the array
for(int i = 0; i < arr.length; i += 1) {
int current = arr[i];
int j = i-1;
while(j >= 0 && current < arr[j]) {
arr[j+1] = arr[j];
j -= 1;
}
arr[j+1] = current;
}
System.out.print("Sorted array: \n");
for(int i = 0; i < arr.length; i += 1) {
System.out.print(arr[i] + " ");
}
}
}