Commit 4f291b3f authored by RONGALI RAVI TEJA's avatar RONGALI RAVI TEJA

change implementation to merge-sort

parent 0fb676da
......@@ -2,16 +2,51 @@
#include<vector>
#include "sorting.h"
using namespace std;
vector<int> sort_custom(vector<int>r){
for(int i=0;i<r.size();i++){
for(int j=r.size()-1;j>=i;j--){
if(r[j-1]>r[j]){
int temp;
temp=r[j-1];
r[j-1]=r[j];
r[j]=temp;
vector<int> merge(vector<int> left, vector<int> right)
{
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;
}
}
}
return r;
}
return result;
}
vector<int> sort_custom(vector<int> m)
{
if (m.size() <= 1)
return m;
vector<int> left, right, result;
int middle = ((int)m.size()+ 1) / 2;
for (int i = 0; i < middle; i++) {
left.push_back(m[i]);
}
for (int i = middle; i < (int)m.size(); i++) {
right.push_back(m[i]);
}
left = sort_custom(left);
right = sort_custom(right);
result = merge(left, right);
return result;
}
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