Okay I have fiddled around with everything and can not find the problem. I am new to c++ and really need help with this. The merge sort works perfectly but for some odd reason will not give all the values. Working with recursive merge sort can be confusing so was hoping I could have this problem solved. Thank you!1
the output when program is ran. ignore the bubble sort:
Here is the input from the image: {41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464, 5705, 28145, 23281, 16827, 9961, 491, 2995, 11942, 4827, 5436}
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector <int> mergeSort(vector <int> data);
vector <int> merge(vector <int> arrayOne, vector <int> arrayTwo);
vector <int> dataList;
vector <int> dataListSorted;
int main()
{
for (int i = 0; i < 20; i++)
{
dataList.push_back(rand());
}
int arrSize = dataList.size();
cout << arrSize << endl;
for (int i = 0; i < arrSize; i++)
{
cout << dataList[i] << " ";
}
cout << endl;
dataListSorted = mergeSort(dataList);
cout << "mergeSort" << endl;
for (int i = 0; i < arrSize; i++)
{
cout << dataListSorted[i] << " ";
}
cout << endl;
}
vector <int> mergeSort(vector <int> data)
{
int arrSize = data.size();
if (arrSize == 1)
{
return data;
}
vector <int> arrayOne;
vector <int> arrayTwo;
for (int i = 0; i < (arrSize / 2); i++)
{
arrayOne.push_back(data[i]);
arrayTwo.push_back(data[i+arrSize/2]);
}
arrayOne = mergeSort(arrayOne);
arrayTwo = mergeSort(arrayTwo);
return merge(arrayOne,arrayTwo);
}
vector <int> merge(vector <int> arrayOne, vector <int> arrayTwo)
{
vector <int> data;
while (arrayOne.size() != 0 && arrayTwo.size() != 0)
{
if (arrayOne[0] > arrayTwo[0])
{
data.push_back(arrayTwo[0]);
arrayTwo.erase(arrayTwo.begin());
}
else
{
data.push_back(arrayOne[0]);
arrayOne.erase(arrayOne.begin());
}
}
while (arrayTwo.size() != 0)
{
data.push_back(arrayTwo[0]);
arrayTwo.erase(arrayTwo.begin());
}
while (arrayOne.size() != 0)
{
data.push_back(arrayOne[0]);
arrayOne.erase(arrayOne.begin());
}
return data;
}