【问题标题】:C++ finding the min location, sort, and swap in a 2D arrayC++ 在二维数组中查找最小位置、排序和交换
【发布时间】:2014-11-18 23:36:42
【问题描述】:

抱歉,如果之前已经回答过这个问题,但我找不到它,因为格式与我的完全不同,或者他们使用的方法与我目前正在学习的方法不同.它们都必须在单独的函数中,而且我还没有学过向量或指针。我已经看到一些以这种方式回答的问题,但目前在课堂上有点进步。

我最紧迫的问题是在尝试获取最小值的位置时。二维数组中的数字。我是否必须做某种类型的大括号或其他东西才能扫描整个数组。一个例子是:位置=索引,J;或位置 = Array[index][J];

或者我必须在 if 语句中做其他事情吗?

抱歉,如果我的代码格式不适合帖子。

  int MinLocation(int Array[][COL], int Row, int COl, int s)`
  {
     int min = max;
    int location = 0;

    for (int index = s; index < Row; index++)
     {
         for (int J = s; J < COL; J++)
         {


           if (Array[index][COL] < min)
           {
               min = Array[index][J];
               location = J;
           }

        }

     }
   return location;
 }



   void Sort(int Array[][COL], int Rows, int COL)
   {

     int Min;
     int MinSpot;
     int current;
     int currentLocation;
     int start;

     for (int index = 0; index < Rows; index++)
     {

        for (int J = 0; J < COL; J++)
        {
          start = index;//Starts at O on the array

          current = Array[index][J];

          currentLocation = index;

          Min = FindMIN(Array, Rows, COL, start);

          MinSpot = MinLocation(Array, Rows, COL, start);

         Swap(Array, currentLocation, MinSpot);

       }

     }
   }
   void Swap(int Array[][COL], int& x, int& y)
   {

     int first, second;


    first = Array[x][COL];
    second = Array[y][COL];


    Array[x][COL] = second;
    Array[y][COL] = first;

   }

【问题讨论】:

  • 你知道如何在一个简单的数组(一维)中找到最小值吗?
  • 是的,我能够让它在一维数组上工作。你想让我也发一下吗?
  • 不,我只是想知道我需要解释多少。

标签: c++ arrays sorting 2d swap


【解决方案1】:

迭代(所谓的)二维数组的最简单方法是使用两个嵌套循环:

for(unsigned int j=0; j<numRows; ++j)
  for(unsigned int k=0; k<numColumns; ++k)
    ... do something with A[j][k] ...

【讨论】:

  • 但我认为我是用我的两个 for 循环来做的。你是说我应该放入一个 do/while 循环吗?
【解决方案2】:

如果你想在特定列中找到最小值,那么你不需要嵌套循环...但是如果你想从整个数组中找到最小值,那么你需要嵌套循环。 而在您的代码中...您要做的就是从数组中选择一个元素并将其与数组的最小值元素交换。

但是你没有在 if 语句中改变数组的 COL 索引。这意味着您只在一列中找到最小元素。

【讨论】:

  • 你的意思是像我的 if 语句中的内容吗?我想我能够找到它的位置。 min = Array[index][COL];
  • 好吧,我试着理解你的意思,然后我又写了一个 if 语句。 if (Array[index][COL] &lt; min) { min = Array[index][COL]; location = index; } 好像没问题,这就是你说的不改变 COL 的意思吗?
  • 首先...告诉我您只想对数组的一列或整个数组进行排序?
  • 好吧,那是稍后,但我确实想对整个数组进行排序。
  • 那么您需要从整个数组中找到最小元素...但是在您的函数 minlocation 中,您的循环仅遍历数组的一部分,从 (s,s) 到 (ROW, COL)在 if 语句中, array[index][col]
猜你喜欢
  • 2018-04-10
  • 2018-07-05
  • 2019-03-31
  • 2015-04-06
  • 2014-02-27
  • 2017-02-13
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多