vendredi 23 février 2018

Using an insertion sort to move ENTIRE ROWS of a 2D dynamic array

This is my first time asking a question on stackoverflow. I would like some help with an insertion sort of a dynamic 2D array. Specifically, I need entire rows to be moved when sorted, not just individual elements. I've gotten close, but the way I have it now seems to make the first step or two, then just quit. Below is what I've done with the function so far, and the test case I'm running it with as well as what the output of the function should be if it's right.

void insertionSort(string **arr, string sortKey, int row, int col)
{
     for(int i = 1; i < row; i++)
     {
          int j = i-1;
          string *key = arr[i];
          for(int k = 0; k < col; k++)
          {
              if(arr[i][k].find(sortKey) != -1)
              {
                  while(j >= 0 && arr[j][k] > arr[i][k])
                  {
                      arr[j+1] = arr[j];
                      j--;
                  }
              }
              arr[j+1] = key;
          }
     }
}

Input: (elements separated by spaces)

id:1234567 first:Mary last:Green DOB:1996-10-03 GPA:4.0
id:1234568 first:Peter last:White DOB:1997-05-22 GPA:3.8 
id:1654238 first:Nick last:Park DOB:1995-08-18 GPA:4.0 
id:1234587 first:Katy last:Green DOB:1995-08-18 GPA:4.0 

Desired Output: (when sorted by first name, which is what param sortKey holds)

id:1234587 first:Katy last:Green DOB:1995-08-18 GPA:4.0 
id:1234567 first:Mary last:Green DOB:1996-10-03 GPA:4.0 
id:1654238 first:Nick last:Park DOB:1995-08-18 GPA:4.0 
id:1234568 first:Peter last:White DOB:1997-05-22 GPA:3.8 

Current Output:

id:1234567 first:Mary last:Green DOB:1996-10-03 GPA:4.0 
id:1654238 first:Nick last:Park DOB:1995-08-18 GPA:4.0 
id:1234587 first:Katy last:Green DOB:1995-08-18 GPA:4.0 
id:1234568 first:Peter last:White DOB:1997-05-22 GPA:3.8 

As you can see, SOME sorting was definitely done. It just didn't finish before it quit. If this were something like a bubble or selection sort where I could just put in a swap function, it'd be fine. But getting this to work for insertion is giving me trouble. Are there any logic errors or missing bits from my code that could help me sort this the rest of the way?

Any help and advice is very much appreciated!

Aucun commentaire:

Enregistrer un commentaire