Insertion Sort
Insertion Sort
Insertion Sort
Insertion sort is a simple sorting algorithm that builds the final sorted array
one element at a time. It works similarly to how you might sort playing cards
in your hands: you pick cards one by one and insert them into the correct
position relative to the already sorted cards.
Algorithm:
1. Start from the second element (index 1) because the first element is
already "sorted."
3. If the current element is smaller than the previous element, swap them.
4. Continue comparing and shifting elements to the right until the current
element is in its correct position.
5. Repeat the process for all elements until the entire array is sorted.
Example:
Step 1: Start with the second element (2). Compare with 5 (first element),
and since 2 < 5, shift 5 to the right and place 2 in the first position.
Step 4: Now, consider 5. It is less than 9 but greater than 2, so shift 9 and
place 5 in the third position.
Time Complexity:
Example
#include <stdio.h>
Int j = I – 1;
Arr[j + 1] = arr[j];
J = j – 1;
Arr[j + 1] = key;
Printf(“%d “, arr[i]);
Printf(“\n”);
}
Int main() {
printArray(arr, n);
insertionSort(arr, n);
printArray(arr, n);
return 0;
Output
2. Bubble Sort
Bubble sort is another simple sorting algorithm that repeatedly steps through
the list, compares adjacent elements, and swaps them if they are in the
wrong order. The process is repeated until the array is sorted. It gets its
name because smaller elements "bubble" to the top (beginning) of the array.
Algorithm:
4. Move to the next pair of adjacent elements and repeat the process until
you reach the end ofthe array.
5. After each complete pass, the largest element in the unsorted portion will
be placed in its correct position.
6. Repeat the process for the remaining unsorted portion of the array.
7. Continue until no swaps are needed, indicating that the array is sorted.
Example:
First Pass
Second Pass:
Third Pass:
Compare 2 and 1: swap them → [1, 2, 5, 5, 6, 9]
Time Complexity:
Insertion Sort tends to perform better than Bubble Sort in practical cases
because fewer swaps are made. It can be more efficient if the data is already
partially sorted.
Both algorithms are easy to understand but inefficient for large datasets, as
their time complexity grows quadratically.
Example :
Input
#include <stdio.h>
Arr[j + 1] = temp;
}
}
Printf(“%d “, arr[i]);
Printf(“\n”);
Int main() {
printArray(arr, n);
bubbleSort(arr, n);
printArray(arr, n);
return 0;
Out put