Insertion Sort, Modern C++ and Others
Third semester of my college started and since it was the starting of year 2015 and I hope to make blogging a regular habit not a resolution because resoultions have become overrated and they rarely work, let’s if it works. Anyways, this semester I have one of the most important subjects Design and Analysis of Algorithms and I plan to write my findings/thoguhts about alogrithms (and their implementations in modern c++) and things I have learned from this course so as I have archived notes for future references.
Insertion Sort
One of the simplest algorithms that’s best for small sets of inputs and based on the intutive method of manual sorting of playing cards. OCW lectures call the current/main index as key and all operations with key as the base.Gist is to start with second element of the array and go till end and each stop insert the element in already sorted list,which can be slightly improved using binary search for finding the insertion in the already sorted array.
Implementation
As with every algorithm you get a psuedocode as part of the tradtion.
Psuedocode
Classic C++
As I was implementing my algorithm I noticed that it was not playing nice with negative numbers so I searched the web for implementations and most of them were same, and it looked this
Making it modern
It pisses me off when people use C like convention,styles and functions in c++ and call it “C with classes” but reality is different, C++ is not what it used to be, it is now modern and has better library support which makes it more readable and efficient. Now this algorithm can be made compact replacing the swapping operation with swap() function present in the
Replacing the for loop for output with the range based for loops
Now we need three headers **
which is definitely shorter than the previous one.
Leveraging the power of STL
While I was searching for algorithms in modern C++ I found this great thread on stackoverflow which discussed many great ways to use inbuilt STL’s and this blog which discussed the implementation in detail, here’s the code
Which fits the whole logic in just two lines. Pretty cool, huh ? Since I am also using ruby so porting the same in ruby dialect won’t be a big issue
That’s all for now :)
Comments