Insertion Sort in Java (With Intuition + Dry run + Code)

Insertion Sort in Java (With Intuition + Dry run + Code)

Why the name insertion sort ?

The name “insertion sort” comes from the way this sorting algorithm works. It maintains a sorted sublist in the lower positions of the list. It iterates through the list, removing one element at a time and finding the correct position to insert it into the sorted sublist. This process continues until the whole list is sorted. The term “insertion” refers to the action of inserting an element into its correct position within the sorted sublist.

Algorithm :

Start with the second element (index 1) of the array.
Compare this element to the one before it. If the previous element is greater, swap the two elements.
Continue comparing the element to the ones before it and swapping as needed until the element is in its correct sorted position.
Move to the next element (index 2) and repeat steps 2-3 until the entire array is sorted.

I will show the working of Insertion sort but make sure to dry run using pen & paper📝

Time Complexity:

Best Case: O(n)
Worst Case: O(n^2)

Space Complexity:

O(1)

Wrapping Up:

Now, congrats, you’ve learned insertion sort 🥳👏
Thanks for reading🥰.
Feel free to comment🖌️ and like the post💓
Follow for more 🤝 && Happy Coding🚀👩‍💻

Don’t forget to check out my other socials :
Github
Twitter(X)
Hashnode
Medium

Leave a Reply

Your email address will not be published. Required fields are marked *