-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpractical03.java
32 lines (29 loc) · 878 Bytes
/
practical03.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
// Sort the given array using Insertion sort
class practical03 {
public static void printArray(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void insertionSort(int arr[]) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
int[] arr = { 15, 45, 31, 42, 11 };
System.out.println("Array before sorting:");
printArray(arr);
System.out.println();
insertionSort(arr);
System.out.println("Array after sorting:");
printArray(arr);
}
}