Day 6: Advanced Sorting Algorithms - Insertion Sort and Merge Sort
Advanced Sorting Algorithms - Insertion Sort and Merge Sort#
Welcome to Day 6 of our 60 Days of Coding Algorithm Challenge! Today, we’ll delve into two more advanced sorting algorithms: Insertion Sort and Merge Sort. These sorting techniques offer different trade-offs in terms of efficiency and complexity.
See them in motion: watch insertion sort and merge sort animate 100 values step by step in our free interactive visualizers.
Insertion Sort#
Insertion Sort is a simple and intuitive sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms like Merge Sort.
How It Works:#
- It iterates through the array and, for each element, inserts it into its correct position relative to the already sorted elements on its left.
Example:#
1def insertion_sort(arr):
2 for i in range(1, len(arr)):
3 key = arr[i]
4 j = i - 1
5 while j >= 0 and key < arr[j]:
6 arr[j + 1] = arr[j]
7 j -= 1
8 arr[j + 1] = key
9 return arr
Time Complexity:#
- Best Case: O(n) when the array is already sorted.
- Average and Worst Case: O(n^2) when the array is in reverse …
Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating