Mastery Unveiled: Insertion Sort Explained with Code Examples and a LeetCode Challenge
Sorting algorithms are the backbone of data organization, and Insertion Sort is a methodical and adaptable technique. Its simplicity and versatility make it a valuable tool in a programmer's arsenal. In this SEO blog, we'll unravel the intricacies of Insertion Sort, provide code examples in Python, explore its time complexity, and conquer a LeetCode challenge using this sorting algorithm.
Demystifying Insertion Sort
Insertion Sort is an in-place, comparison-based sorting algorithm that constructs the final sorted array one element at a time. It systematically places each element in its proper position within the existing sorted portion of the array.
Insertion Sort at a Glance:
Begin with the second element, treating it as the 'key.'
Compare the 'key' with elements in the sorted part, shifting larger elements to the right.
Insert the 'key' into its correct position within the sorted portion.
Repeat until all elements are sorted.
Python Implementation of Insertion Sort
Let's dive into the Python implementation of Insertion Sort:
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
Analyzing Time Complexity
Insertion Sort's time complexity is O(n^2) in the worst case, making it more suitable for smaller datasets. The nested loop structure, coupled with element shifting, contributes to this complexity.
Solving a LeetCode Problem using Insertion Sort
Problem: LeetCode 147 - Insertion Sort List
Given the head of a singly linked list, sort the list using the Insertion Sort algorithm.
Solution using Insertion Sort: Traverse the linked list and insert each node into the sorted portion of the list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertion_sort_list(head):
dummy = ListNode()
current = head
while current:
prev = dummy
while prev.next and prev.next.val < current.val:
prev = prev.next
temp = current.next
current.next = prev.next
prev.next = current
current = temp
return dummy.next
Conclusion
Insertion Sort, with its adaptability and practicality, offers valuable insights into sorting. By grasping its logic, implementing it in Python, and solving real-world challenges like the LeetCode problem, you gain a versatile sorting tool. Whether you're a coding novice exploring sorting or an experienced programmer revisiting the basics, Insertion Sort strikes a balance between simplicity and effectiveness.
Happy coding and sorting! ๐๐๐ง
Subscribe to my newsletter
Read articles from Ayesha Irshad directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ayesha Irshad
Ayesha Irshad
I am a Developer Program Member at GitHub, where I collaborate with a global community of developers and contribute to open source projects that advance the field of Artificial Intelligence (AI). I am passionate about learning new skills and technologies, and I have completed multiple certifications in Data Science, Python, and Java from DataCamp and Udemy. I am also pursuing my Bachelor's degree in AI at National University of Computer and Emerging Sciences (FAST NUCES), where I have gained theoretical and practical knowledge of Machine Learning, Neural Networks, and Data Analysis. Additionally, I have worked as an AI Trainee at Scale AI, where I reviewed and labeled data for various AI applications. Through these experiences, I have developed competencies in Supervised Learning, Data Science, and Artificial Neural Networks. My goal is to apply my skills and knowledge to solve real-world problems and create positive impact with AI.