Skip to content

Commit c0601d0

Browse files
author
Farheen Shabbir Shaikh
committed
Add Insertion Sort algorithm in Java with comments
1 parent f405669 commit c0601d0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Sorting/InsertionSort.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* InsertionSort.java
3+
* This program implements the Insertion Sort algorithm.
4+
* Time Complexity: O(n^2) in worst case, O(n) in best case (already sorted).
5+
*/
6+
7+
public class InsertionSort {
8+
9+
public static void insertionSort(int[] arr) {
10+
// Loop from the second element to the end
11+
for (int i = 1; i < arr.length; i++) {
12+
int key = arr[i]; // Store the current element to be inserted
13+
int j = i - 1;
14+
15+
// Move elements of arr[0..i-1], that are greater than key,
16+
// to one position ahead of their current position
17+
while (j >= 0 && arr[j] > key) {
18+
arr[j + 1] = arr[j]; // Shift element to the right
19+
j = j - 1;
20+
}
21+
arr[j + 1] = key; // Insert the key into its correct position
22+
}
23+
}
24+
25+
public static void main(String[] args) {
26+
int[] arr = {29, 10, 14, 37, 13};
27+
insertionSort(arr);
28+
System.out.println("Sorted array:");
29+
for (int num : arr) {
30+
System.out.print(num + " ");
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)