Skip to content

Instantly share code, notes, and snippets.

@tomauty
Created February 16, 2012 19:02
Show Gist options
  • Save tomauty/1847043 to your computer and use it in GitHub Desktop.
Save tomauty/1847043 to your computer and use it in GitHub Desktop.
Tom's Merge Sort
void MultiSort::mergeSort ( CSVFile &csv, vector<int> &keys )
{
//If vector size is 1, return
if (csv.get_numRows() <= 1)
{
return;
}
//Else split into two separate subvectors
CSVFile left;
CSVFile right;
int middle = csv.get_numRows() / 2;
for (int i = 0; i < middle; i++ )
{
left.add ( csv.get_row(i) );
}
for (int j = middle; j < csv.get_numRows(); j++)
{
right.add ( csv.get_row(j) );
}
//Call mergesort to split until subvector size is 1
mergeSort(left, keys);
mergeSort(right, keys);
//Merge subvectors returned from prior calls to mergesort
//Return the resulting merged subvector
csv = merge(left, right, keys);
} /* ----- end of method MultiSort::mergeSort ----- */
CSVFile MultiSort::merge ( CSVFile &left, CSVFile &right, vector<int> &keys )
{
CSVFile result;
while ( left.get_numRows() > 0 || right.get_numRows() > 0 )
{
if ( left.get_numRows() > 0 && right.get_numRows() > 0 )
{
if ( left.get_field_range(0, keys) <=
right.get_field_range(0, keys) )
{
result.add ( left.get_row(0) );
left.erase( left );
}
else
{
result.add ( right.get_row(0) );
right.erase ( right );
}
}
else if ( left.get_numRows() > 0 )
{
result.add ( left.get_row(0) );
left.erase ( left );
}
else if ( right.get_numRows() > 0 )
{
result.add ( right.get_row(0) );
right.erase ( right );
}
}
return result;
} /* ----- end of method MultiSort::merge ----- */
/* It crashes when trying to erase from right towards the end of the sort routine. Here's the erase function */
void CSVFile::erase ( CSVFile csv )
{
cout << "deleting ";
cout << rows[row] << endl;
rows.erase( rows.begin() + csv.begin());
numRows--;
}
@tomauty
Copy link
Author

tomauty commented Feb 16, 2012

void CSVFile::erase ( CSVFile &csv )
{
    vector<string>::iterator it = rows.begin();
    cout << "deleting ";
        rows.erase( it );
        numRows--;  
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment