
Insertion Sort is a simple and intuitive sorting algorithm. It builds the sorted portion of the array one element at a time by comparing and inserting elements into their correct position.
import java.util.Arrays;
public class InsertionSort {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
// Store the current element
int key = arr[i];
int j = i - 1;
// Move elements greater than key one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
// Insert the current element at its correct position
arr[j + 1] = key;
}
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6};
System.out.println("Original Array: " + Arrays.toString(arr));
insertionSort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
}
}
def insertion_sort(arr):
# Traverse from the second element to the last
for i in range(1, len(arr)):
# Store the current element
key = arr[i]
j = i - 1
# Shift elements that are greater than key to the right
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
# Place the key at its correct position
arr[j + 1] = key
# Example usage
if __name__ == "__main__":
arr = [12, 11, 13, 5, 6]
print("Original Array:", arr)
insertion_sort(arr)
print("Sorted Array:", arr)
Insertion Sort is used in scenarios where:
While Insertion Sort is straightforward and useful for small or partially sorted datasets, it is inefficient for larger datasets. Advanced algorithms like Merge Sort, Quick Sort, or Heap Sort are better suited for large arrays.
When analyzing a stock, one of the first financial indicators you’ll encounter is EPS, or Earnings Per Share. It’s one… Read More
When you look at a stock’s profile on a financial website, one of the first things you’ll see is its… Read More
In the world of open-source software, simplicity and flexibility are often just as important as legal protection. That’s why the… Read More
If you want your software to be open source, but still compatible with commercial use—and not as restrictive as the… Read More
When it comes to open-source software, developers and businesses alike need licenses that balance freedom, legal clarity, and long-term security.… Read More
If you’re working on open-source projects or choosing third-party libraries for your software, understanding software licenses is essential. Among the… Read More