Insertion sort
Insertion Sort Insertion sort is a simple yet effective sorting algorithm that works by inserting each element of the list into its correct position in the s...
Insertion Sort Insertion sort is a simple yet effective sorting algorithm that works by inserting each element of the list into its correct position in the s...
Insertion sort is a simple yet effective sorting algorithm that works by inserting each element of the list into its correct position in the sorted sublist.
Algorithm:
Start: Find the first element in the list.
Compare: Compare it to the second element in the list.
Move: Move the first element one position to the right.
Repeat: Repeat steps 2 and 3 for the second element, moving it one position to the right each time.
Continue: Continue this process until you reach the last element in the list.
Merge: Merge the current sublist with the next sublist in sorted order.
Example:
Input: 7, 2, 8, 3, 1
Steps:
Start with the first element (7) as the first element in the sublist.
Compare it to the second element (2). Move it one position to the right.
Repeat with the second element (8). Move it one position to the right.
Repeat with the third element (3). Move it one position to the right.
Repeat with the fourth element (1). Move it one position to the right.
Merge the current sublist with the next sublist containing the elements 2, 3, and 7.
Output: 2, 3, 7, 8
Time complexity: O(n), where n is the length of the input list. This means that the algorithm will run in linear time, with each element taking O(n) time to be processed.
Advantages:
Simple and easy to understand.
Efficient for large datasets.
Stable, meaning the result is the same regardless of the order of equal elements.
Disadvantages:
Not as efficient for small datasets.
Can be slow for sorting large datasets when the number of swaps is greater than the number of elements.
Not as efficient for sorting mixed-up lists