-3
void bubbleSort(int ar1[10], int logicalSize)
{
   int tempHolder = 0; 
   for (int i = logicalSize; i >= 2; i--)
   {
      for(int i2 = 0; i2 < logicalSize-i2; i++)
      {
         if (ar1[i2 + 1] < ar1[i2])
         {
            tempHolder = ar1[i2]; 
            ar1[i2] = ar1[i2 + 1]; 
            ar1[i2 + 1] = tempHolder; 
         }

      }
   }
   cout << "The array in sorted order: " << endl; 
   for(int i2 = 0; i2 <= 10; i2++)
   {
      cout << ar1[i2] << endl;
   }
} 

int main () 
{
   int arry1[10]; 
   arry1[0] = 8;
   arry1[1] = 56;
   arry1[2] = 4;
   arry1[3] = 25;
   arry1[4] = 45;
   arry1[5] = 92;
   arry1[6] = 11;
   arry1[7] = 1;
   arry1[8] = 78;
   arry1[9] = 66;
   arry1[10] = 24;

   cout << "The array in its original order: " << endl; 
   for (int i = 0; i <= 10; i++)
   {
      cout << arry1[i] << endl;
   }

   bubbleSort(arry1, 11);

   cout << "The array in sorted order: " << endl; 
   for(int i2 = 0; i2 <= 10; i2++)
   {
      cout << arry1[i2] << endl;
   }


   return 0;
} 

我似乎无法让我的冒泡排序工作。代码看起来不错,我的数组似乎设置正确。任何人都可以帮我解决这个问题吗?我在 mt 函数中的循环是否设置不正确?还是循环中发生的事情导致我的错误发生?

4

2 回答 2

1
  1. 你有缓冲区溢出(11 个元素而不是 10 个)
  2. 您需要增加 i2 in for(int i2 = 0; i2 < logicalSize-i2; i++),如下所示:for(int i2 = 0; i2 < logicalSize-i2; i2++)
  3. 您需要迭代直到< 10not <= 10
  4. bubbleSort(arry1, 11)应该bubbleSort(arry1, 10)
  5. 你可能希望你的for循环像(一个糟糕的冒泡排序版本):

     for (int i = 0; i < logicalSize; i++)
     {
         for(int i2 = 0; i2 < logicalSize; i2++)
         {
         }
     }
    
于 2013-07-29T20:20:09.190 回答
0

您为 10 个成员声明了数组,因此您的索引为 0 到 9。所以arry1[10]=24;数组溢出。您的函数中存在一些逻辑错误, bubbleSort 这使您的循环无限。

#include <iostream>

using namespace std;

void bubbleSort(int ar1[], int logicalSize)
{
   int tempHolder = 0;    //logical mistake , which makes your loop infinite
   for (int i = 0; i < logicalSize; i++)
   {
      for(int i2 = 0; i2 < logicalSize-1; i2++)
      {
         if (ar1[i2 + 1] < ar1[i2])
         {
            tempHolder = ar1[i2];
            ar1[i2] = ar1[i2 + 1];
            ar1[i2 + 1] = tempHolder;
         }

      }
   }
   cout << "The array in sorted order: " << endl;
   for(int i2 = 0; i2 < 10; i2++)
   {
      cout << ar1[i2] << endl;
   }
}

int main ()
{
   int arry1[10];
   arry1[0] = 8;
   arry1[1] = 56;
   arry1[2] = 4;
   arry1[3] = 25;
   arry1[4] = 45;
   arry1[5] = 92;
   arry1[6] = 11;
   arry1[7] = 1;
   arry1[8] = 78;
   arry1[9] = 66;
  // arry1[10] = 24;  //array overflow

   cout << "The array in its original order: " << endl;
   for (int i = 0; i < 10; i++)
   {
      cout << arry1[i] << endl;
   }

   bubbleSort(arry1, 10);

   cout << "The array in sorted order: " << endl;
   for(int i2 = 0; i2 < 10; i2++)
   {
      cout << arry1[i2] << endl;
   }


   return 0;
}
于 2013-07-29T20:47:46.840 回答