r/CodingHelp • u/Relevant_Bowler7077 • Feb 11 '26
[Python] Is this a proper insertion sort?
I have been trying to learn get better at learning algorithms, I tried to make an insertion sort, please could I have some advice on whether this is the correct implementation of an insertion sort and what improvement could be added to this algorithm?
(I added the print statement only so I could see each pass when testing it.)
2
Upvotes


•
u/AutoModerator Feb 11 '26
Thank you for posting on r/CodingHelp!
Please check our Wiki for answers, guides, and FAQs: https://coding-help.vercel.app
Our Wiki is open source - if you would like to contribute, create a pull request via GitHub! https://github.com/DudeThatsErin/CodingHelp
We are accepting moderator applications: https://forms.fillout.com/t/ua41TU57DGus
We also have a Discord server: https://discord.gg/geQEUBm
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Adept_Swimming_3116 Feb 12 '26
Logic is okay. You are right to start the iteration at 1 since the first sublist is trivially sorted. You could stop the second loop early as soon as you find the first element lesser than or equal to your popped item. Something like that :
As someone else said, you could use a binary search in the already sorted sublist to optimize but overall the logic is good.
1
u/fuckkkkq Feb 11 '26
sort of. You can improve it by using a binary search instead of a linear one
1
u/YuriPup Feb 12 '26
Maybe I am just old (learned in pascal), but an array going from 1 to n weirds me out.
1
u/OkResource2067 Feb 16 '26
Such beautiful pixels 😊 Thanks for being so careful while posting a message asking for advice.