【问题标题】:Determining Sorting Algorithm Output [closed]确定排序算法输出
【发布时间】:2021-04-29 17:51:21
【问题描述】:

我无法确定这个 void 函数的输出,该函数应该对数组进行排序 [67, 57, 32, 70, 57] 大小 = 5。

我知道它在第 4 行运行了四次 for 循环,但是每次 for 循环的一次迭代完成时,数组会发生什么变化?非常感谢任何帮助,谢谢!

1. void selectionSort(int list[], int size)
2. {
3.    int i, j, temp, minIndex;
4.    for (i = 0; i < size-1; i++)
5.    {
6.       minIndex = i;
7.        for (j = i+1; j < size; j++)
8.        {
9.            if (list[j] < list[minIndex])
10.         {
11.            minIndex = j;
12.         }
13.      }
14.      temp = list[i];
15.      list[i] = list[minIndex];
16.      list[minIndex] = temp;
17.   }
18.} 

示例:第 4 行 for 循环的第一次迭代完成后 int list[] 是什么?

这是我在 IDE 中使用的代码:

    int list[5]={67,57,32,70,57};
int size =5;
 {
   int i, j, temp, minIndex;
   for (i = 0; i < size-1; i++)
   {
      minIndex = i;
      for (j = i+1; j < size; j++)
       {
           if (list[j] < list[minIndex])
       {
           minIndex = j;
       }
      }
      temp = list[i];
      list[i] = list[minIndex];
     list[minIndex] = temp;
      temp = list[i];
      list[i] = list[minIndex];
      list[minIndex] = temp;
     cout << list[0] << " "<< list[1] << " "<< list[2] << " "<< list[3] << " "<< list[4] << " " << endl;
 }
}   
}

但是,它每次都会打印出 [67 57 32 70 57]。

【问题讨论】:

  • 你试过了吗?你有没有去看看它在做什么?
  • 我尝试在 IDE 中运行它,但每次都得到相同的代码行,所以我认为我可能做错了什么。
  • 如果您使用 IDE 单步执行,您应该能够在外循环的第一次迭代后看到 list 数组的内容。
  • 以上语句表明您错误地使用了调试器。当 ChrisMM 说“step”时,他的意思是使用调试器的 step 功能将程序推进一步。您“单步执行”程序并记下它在每个步骤中的作用。它改变了哪些变量?走了什么路。使用这些注释可以更好地理解程序的功能。
  • 您总是可以在循环结束时打印出数组来查看它的样子。例如,在第 17 行之前: for (int k = 0; k

标签: c++ arrays sorting


【解决方案1】:

好的,调试程序或获得类似答案的最简单方法是添加输出语句。你问到循环结束时数组是什么样子的:

void selectionSort(int list[], int size)
{
    int i, j, temp, minIndex;
    for (i = 0; i < size-1; i++)
    {
       minIndex = i;
        for (j = i+1; j < size; j++)
        {
            if (list[j] < list[minIndex])
         {
            minIndex = j;
         }
      }
      temp = list[i];
      list[i] = list[minIndex];
      list[minIndex] = temp;
   }

   std::cout << "Array at bottom of loop with index: " << i << " == ";
   for (int index = 0; index < size; ++index) {
       cout < "  " << list[index];
   }
   cout << endl;
} 

您可以在有问题的地方添加其他类型的输出语句。有时我发现做这样的事情对我来说比使用调试器要快得多。例如,如有必要,我可能会在 if 语句之前放置一个 cout,而在 if 代码中放置另一个。

无需太多输出行,您就可以更好地了解您的代码在做什么。

精通调试器很有价值,但有时你就是做不到。

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多