Commit 40544606 authored by meethkr's avatar meethkr

change implementation to merge-sort

parent b1e0aaa8
CC = g++
all: main.o sorting.o
g++ main.o sorting.o -o main
main.o: main.cpp sorting.h
g++ -I . -c main.cpp
sorting.o: sorting.cpp sorting.h
g++ -I . -c sorting.cpp
clean:
rm -rf *.o
...@@ -3,34 +3,24 @@ ...@@ -3,34 +3,24 @@
#include "sorting.h" #include "sorting.h"
using namespace std; using namespace std;
vector<int> sort_custom(vector<int>);
void bubbleSort(vector<int>& a);
void printVector(vector<int> a);
int main(int argc, char const *argv[]) int main(int argc, char const *argv[])
{ {
vector<int> a; vector<int> a;
int num = 0; int num = 0;
while (num != -1) while (num != -1)
{ {
std::cin>>num; std::cin>>num;
if (num != -1) if (num != -1)
//add elements to the vector container
a.push_back(num); a.push_back(num);
} }
//printVector(a);
bubbleSort(a);
printVector(a); a = sort_custom(a);
}
void printVector(vector<int> a)
{
for (int i=0; i <a.size(); i++) for (int i=0; i <a.size(); i++)
{ {
cout<<a[i]<<" "; cout<<a[i]<<" ";
} }
} }
#include <iostream>
#include <vector>
using namespace std; using namespace std;
#include <vector>
void bubbleSort(vector<int>& a) vector<int> merge(vector<int> left, vector<int> right)
{ {
bool swapp = true; vector<int> result;
while(swapp){ while ((int)left.size() > 0 || (int)right.size() > 0) {
swapp = false; if ((int)left.size() > 0 && (int)right.size() > 0) {
for (size_t i = 0; i < a.size()-1; i++) { if ((int)left.front() <= (int)right.front()) {
if (a[i]>a[i+1] ){ result.push_back((int)left.front());
a[i] += a[i+1]; left.erase(left.begin());
a[i+1] = a[i] - a[i+1];
a[i] -=a[i+1];
swapp = true;
} }
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 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]);
} }
// return a;
left = sort_custom(left);
right = sort_custom(right);
result = merge(left, right);
return result;
} }
using namespace std; using namespace std;
void bubbleSort(vector<int>& a); vector<int> sort_custom(vector<int>);
void printVector(vector<int> a);
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