Hack Forums
[C] Issues With Merge Sort Function - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] Issues With Merge Sort Function (/showthread.php?tid=6051831)



Issues With Merge Sort Function - Sмℯґƒ - Feb 22, 2020

So for a class assignment we have to merge sort a vector of custom classes called Record. I think I'm having an issue when it comes to merging back together the split L/R sections.
Heres my driver code:
Code
void CensusData::mergeSort(int /*type*/)
{
  mergeSortPop(data, 0, data.size() - 1);
}
And heres the rest of the merge sort algo:
Code
void CensusData::mergeSortPop(vector<Record*>, int p, int r)
{
  if(p < r)
  {
    int q = (p+(r-1))/2;

    mergeSortPop(data, p, q);
    mergeSortPop(data, q + 1, r);

    mergePop(data, p, q, r);
  }
}
void CensusData::mergePop(vector<Record*> data, int p, int q, int r)
{
  int i, j, k;
  int n1 = q - p + 1;
  int n2 = r -q;

  vector<Record*> left;
  vector<Record*> right;
  for(i = 0; i < n1; i++)
  {
    left.push_back(data[p + i]);
    std::cout << "Pushing back" << *(data[p+i]) << "\n";
  }
  for(j = 0; j < n2; j++)
  {
    right.push_back(data[q + 1 + j]);
  }
  i = 0; j = 0; k = p;
  while(i < n1 && j < n2)
  {
    if(left[i]->population <= right[j]->population)
    {
      *(data[k]) = *(left[i]);
      i++;
    }else
    {
      *(data[k]) = *(right[j]);
      j++;
    }
    k++;
  }
  while(i < n1)
  {
    (data[k]) = (left[i]);
    i++;
    k++;
  }
  while(j < n2)
  {
    (data[k]) = (right[j]);
    j++;
    k++;
  }
}
Record holds pointers to population for each record created. Thanks guys.


RE: Issues With Merge Sort Function - SIM-3991524 - Feb 22, 2020

Maybe you could post more of the code?

Working mergesort with your Record class
Spoiler (Click to View)

Example output
Spoiler (Click to View)