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 :

  1. Start with the second element (index 1) of the array.
  2. Compare this element to the one before it. If the previous element is greater, swap the two elements.
  3. Continue comparing the element to the ones before it and swapping as needed until the element is in its correct sorted position.
  4. 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📝

insertion-sort1

insertion-sort2

insertion-sort3

insertion-sort4

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


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

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

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Free & easy ad network.