forked from he4rt/he4rtoberfest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort
39 lines (31 loc) · 1.02 KB
/
InsertionSort
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
public class InsertionSort {
// Function to perform insertion sort
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
System.out.println("Original Array:");
printArray(arr);
insertionSort(arr);
System.out.println("\nSorted Array (Insertion Sort):");
printArray(arr);
}
// Function to print an array
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
}