Welcome to the fascinating world of Data Structures and Algorithms! Today, we'll be diving into the depths of Insertion Sort, a fundamental sorting algorithm used to organize data in a way that can significantly improve the efficiency of your code.
Insertion Sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It works by inserting each element into its correct position in a sorted list, which we create during the sorting process.
Imagine you're organizing a deck of cards. Instead of shuffling and then sorting them like a traditional sorting algorithm, you'd insert each new card into its correct position in a smaller, already sorted stack. That's exactly what Insertion Sort does!
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Test the function
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print(arr) # Output: [5, 6, 11, 12, 13]function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
// Test the function
let arr = [12, 11, 13, 5, 6];
insertionSort(arr);
console.log(arr); // Output: [5, 6, 11, 12, 13]
}Which of the following sorting algorithms builds the final sorted array one item at a time?
Insertion Sort is best suited for:
Keep learning, and remember: practice makes perfect! Happy coding! š