Commit 252d08e3 authored by Varshitha Mannem's avatar Varshitha Mannem

update merge-sort to reflect API update

parent 384d5fcd
#include "sorting.h"
#include"sorting.h"
vector<int> merge(vector<int> left, vector<int> right)
void merge(vector<int>& v, int first, int mid, int last)
{
vector<int> result;
while ((int)left.size() > 0 || (int)right.size() > 0) {
if ((int)left.size() > 0 && (int)right.size() > 0) {
if ((int)left.front() <= (int)right.front()) {
result.push_back((int)left.front());
left.erase(left.begin());
}
else {
result.push_back((int)right.front());
right.erase(right.begin());
}
} else if ((int)left.size() > 0) {
for (int i = 0; i < (int)left.size(); i++)
result.push_back(left[i]);
break;
} else if ((int)right.size() > 0) {
for (int i = 0; i < (int)right.size(); i++)
result.push_back(right[i]);
break;
// temporary vector to merge the sorted sublists
vector<int> tempVector;
int indexA, indexB, indexV;
// set indexA to scan sublistA (index range [first,mid)
// and indexB to scan sublistB (index range [mid, last)
indexA = first;
indexB = mid;
// while both sublists are not exhausted, compare v[indexA] and
// v[indexB]copy the smaller to vector temp using push_back()
while (indexA < mid && indexB < last)
if (v[indexA] < v[indexB])
{
tempVector.push_back(v[indexA]); // copy element to temp
indexA++; // increment indexA
}
else
{
tempVector.push_back(v[indexB]); // copy element to temp
indexB++; // increment indexB
}
}
return result;
// copy the tail of the sublist that is not exhausted
while (indexA < mid)
{
tempVector.push_back(v[indexA]);
indexA++;
}
while (indexB < last)
{
tempVector.push_back(v[indexB]);
indexB++;
}
// copy vector tempVector using indexV to vector v using indexA
// which is initially set to first
indexA = first;
// copy elements from temporary vector to original list
for (indexV = 0; indexV < tempVector.size(); indexV++)
{
v[indexA] = tempVector [indexV];
indexA++;
}
}
vector<int> sort_custom(vector<int> m)
vector<int> sort_custom (vector<int>
v, int first, int last)
{
if (m.size() <= 1)
return m;
vector<int> left, right, result;
int mid = ((int)m.size()+ 1) / 2;
for (int i = 0; i < mid; i++) {
left.push_back(m[i]);
}
for (int i = mid; i < (int)m.size(); i++) {
right.push_back(m[i]);
}
left = sort_custom(left);
right = sort_custom(right);
result = merge(left, right);
return result;
}
// if the sublist has more than 1 element continue
if (first + 1 < last)
{
// for sublists of size 2 or more, call mergeSort()
// for the left and right sublists and then
// merge the sorted sublists using merge()
int midpt = (last + first) / 2;
sort_custom(v, first, midpt);
sort_custom(v, midpt, last);
merge(v, first, midpt, last);
}
return v;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment