Skip to content

Instantly share code, notes, and snippets.

@Ex094
Last active December 28, 2015 21:19
Show Gist options
  • Save Ex094/7563704 to your computer and use it in GitHub Desktop.
Save Ex094/7563704 to your computer and use it in GitHub Desktop.
My Merge Sort Implementation in C++
#include "stdafx.h"
#include "iostream"
#include "vector"
std::vector<int> merge_list(std::vector<int> left, std::vector<int> right) {
//This vector holds all the items in sorted form at the end
std::vector<int>result;
//These variables will be used to iterate through the items
int go_left = 0, go_right = 0;
//Compare the size of the respective vectors until none of the item is left to be sorted
while (go_left < left.size() && go_right < right.size()) {
//Then compare the first 2
if (left[go_left] <= right[go_right]) {
//The smaller item gets inserted into the result vector
result.push_back(left[go_left]);
//Increase by 1
go_left++;
}
else {
//This is the part where the smaller item from the right vector gets inserted
result.push_back(right[go_right]);
//Increase by 1
go_right++;
}
}
//Insert the rest of the items till the point where none remains to be sorted
while (go_left < left.size()) //For the left vector
{
result.push_back(left[go_left]); //Insert into result
go_left++;//Increase by 1
}
while (go_right < right.size())//For the right vector
{
result.push_back(right[go_right]); //Insert into result
go_right++;//Increase by 1
}
//This finally returns the resultant vector (It might be the sublist or completly sorted) :)
return result;
}
std::vector<int> merge_sort(std::vector<int> list) {
//If the size(Number of items) is 1, Consider the list sorted
if (list.size() <= 1) return list;
//Find the midddle item of the list
int mid = (list.size() / 2);
//Vector to add items before the middle part
std::vector<int>left;
//Vector to add items after the middle part
std::vector<int>right;
//Vector iterator to loop through the vector and find the middle part and copy the items before it
for (std::vector<int>::const_iterator it = list.begin(), end = list.end() - mid; it != end; ++it) left.push_back(*it);
//Vector iterator to loop through the vector and find the middle part and copy the items after it
for (std::vector<int>::const_iterator it = list.begin() + mid, end = list.end(); it != end; ++it) right.push_back(*it);
//Recursive call to further merge the lists
right = merge_sort(right);
left = merge_sort(left);
//Call the merge list function and return the sorted list
return merge_list(left, right);
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> x = { 5, 90, 10, 18, 100, 201, 1, 11 };
std::vector<int> sorted = merge_sort(x);
std::cout << "Your sorted List is: " << "\n";
for (std::vector<int>::const_iterator it = sorted.begin(), end = sorted.end(); it != end; ++it){
std::cout << " " << *it << "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment