Final answer:
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It works by considering one element at a time and inserting it into its correct position within the array.
Step-by-step explanation:
Insertion Sort
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It works by considering one element at a time and inserting it into its correct position within the array.
Let's go through the steps of insertion sort for the array [3, 2, 5, 4, 1]:
- Initially, the first element, 3, is considered sorted.
- Next, the second element, 2, is compared with the first element. Since 2 is smaller, it is moved to the left of 3, resulting in the array [2, 3, 5, 4, 1].
- Now, the third element, 5, is compared with the sorted elements to its left. It remains in its position since it is already larger than 2 but smaller than 3.
- The fourth element, 4, is inserted to its correct position by shifting 5 to the right, resulting in [2, 3, 4, 5, 1].
- Finally, the fifth element, 1, is compared with the sorted elements to its left and inserted to its correct position, resulting in the sorted array [1, 2, 3, 4, 5].
So, the contents of the array during the insertion sort process are:
- [3, 2, 5, 4, 1] (Initial array)
- [2, 3, 5, 4, 1]
- [2, 3, 5, 4, 1]
- [2, 3, 4, 5, 1]
- [1, 2, 3, 4, 5] (Sorted array)