So this is my second post in implementing and learning (hopefully) some of the fundamentals algorithms
of Computer Science. This time it’s Merge Sort , which uses the Divide and Conquer approach to give the result within
O (n log(n)) . MIT’s OCW has a great series of lecture on the same and I loved the teaching style of Prof. Charles Leiserson, he simplifies most of the stuff plus he’s the L in the famous CLRS.
Well approach of merge sort is simple and quite powerful and lecture made it look easy, but I have this weak point when it comes to implementation of some powerful and recursive algorithms (gotta improve that).
Implementation
As I said I am not good at implementing algorithms, so I searched the web for implementation and found a great one at
BogotoBogo, anyways gist of the algorithm can be laid out concisely
in the pseudocode
PseudoCode
This is for the Top Down implementation taken from Wikipedia
Divide part
Conquer and Merge Part
##In simple words
C++
This code works flawlessly but it can be shortened and improved, like removing all the c-style casting (int) , since
removing doesn’t breaks the code. Replacing ||, && with actual words like or, and .
Replacing the print fucntion by a lambda. So instead of writing print like
we can write it like this, using the range based for loops
or using the awesome lambdas
Instead of having an extra vector to hold the merged vector we can directly return the result.
Replacing the raw loops used for complete copy by range based loops or for_each
So instead of doing this
We can do this
We can also vector constructor to perform the copy but for this our vector has to created at the time of copying which I don’t want
or I don’t know the proper way to do this :( . Using the copy algorithm, it will look like
Replacing the partial copy using raw loops with either for_each or copy
This seems readable as copy copies in the way [begin,last) which makes it exclusive of last element and is picked up the right side
Also erasing the old vector after copying in merge() can help clear memory
We can make it more efficient by avoiding the copy and using move semantics to move the value saving temporary copies, although I am
not sure whether it helps or not. So, to every return statement add the move() function.
Autofy everything
My most favourite feature of C++ 11 is the auto which deduces the type using some smart moves, and it can drastically improve the
quality of the code but in C++ 11 signature of a function can't be autofied :( but C++14 overcomes this and allows
auto to be used in fuction as well as lambdas, C++14 can be enabled using -std=c++14 or -std=c++1y , for me sadly c++14 doesn't works
but the depreceated c++1y works.
Now code becomes
which looks good and readable :)
However, it may or may not be the best or efficient of doing this, you have been warned.
Comments