Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void MergeSort(vector<int> &vec)
- {
- //if the vector has more than 1 element
- if(vec.size() > 1)
- {
- //separate the vector into two equal vectors
- vector<int> left(vec.begin(), vec.begin() + vec.size() / 2);
- vector<int> right(vec.begin() + vec.size() / 2, vec.end());
- //recursively call MergeSort for each part of the vector
- MergeSort(left);
- MergeSort(right);
- //make room for the new elements to be added
- vec.clear();
- //as long as both the left and the right vectors have elements
- //in them, put the smallest of each into vec one by one
- while (!left.empty() && !right.empty())
- {
- if(left[0] < right[0])
- {
- vec.push_back(left[0]);
- left.erase(left.begin());
- }
- else
- {
- vec.push_back(right[0]);
- right.erase(right.begin());
- }
- }
- //if there are no more elements in the left vector
- // put all those from the right vector directly into vec
- while(left.empty() && !right.empty())
- {
- vec.push_back(right[0]);
- right.erase(right.begin());
- }
- //the same when there are no more elements in the right vector
- while(!left.empty() && right.empty())
- {
- vec.push_back(left[0]);
- left.erase(left.begin());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement