使用插入排序移动2D动态数组的整个行

时间:2018-02-23 21:01:38

标签: c++11 rows dynamic-arrays insertion-sort

这是我第一次在stackoverflow上提问。我想要一些插入动态2D数组的帮助。具体来说,我需要在排序时移动整行,而不仅仅是单个元素。我已经接近了,但我现在拥有它的方式似乎是第一步或第二步,然后就退出了。下面是我到目前为止所做的功能,以及运行它的测试用例以及如果正确的话,功能的输出应该是什么。

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;
          }
     }
}

输入:(以空格分隔的元素)

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 

所需输出:(按名字排序时,这是param sortKey所持有的)

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 

当前输出:

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 

正如您所看到的,某些排序肯定已经完成。在它退出之前它还没有完成。如果这是一个类似于泡泡或选择排序的东西,我可以放入交换功能,它就没事了。但让这个插入工作是给我带来麻烦。我的代码中是否存在任何逻辑错误或缺少的位,这可以帮助我对其余部分进行排序?

非常感谢任何帮助和建议!

0 个答案:

没有答案