Python Algoritm – Insertion Sort with Python

As I have already mentioned, the following 2 months I will be dealing with algorithms! Thus, I have enlisted myself in a course for them and I will be spamming my site constantly with some useful (mainly for me) stuff for algorithms.

As far as all the books for algorithms start with a standard introduction for algorithms, I have decided to solve one of the introduction problems. With Python. The introduction problem was a simple insertion sorting, which I considered an interesting subject in Python.Python

So, what do we have? We have to sort a string, by its values in the ascii table. Pretty trivial, but until this moment I was not thinking how this is done. Without reading the whole ready solution, I managed to come up with something working, which was ok for me. As far as I am not using IDE for Python (it is too easy to program, if you use one), I am always printing a lot of stuff like an old-fashioned coder. So, I started to think a lot. And after about one hour of trial and error (including a coffee pause), I have come up with the solution of two embedded for-loops. Not fascinating, but it was working and it was what people call insertion sorting algorithm. Thus, this is how it looked like, with a lot of printing from my console:


Anyway, the code is really trivial and easy to understand, if you disregard the printing. It worths mentioning that in Python strings are immutable, that is why I have converted them to a list and then I printed it as a string. Another interesting thing in the code is the way to swap values in list in Python. Something like a,b = b,a which I found really nice.

Last but not least, here comes the code, enjoy it:


Tagged with: , ,