我的冒泡排序代码出了什么问题?

时间:2013-07-29 20:17:57

标签: c++

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函数循环是否设置错误?或者是在循环中发生什么导致我的错误发生?

2 个答案:

答案 0 :(得分:1)

  1. 你有缓冲区溢出(11个元素而不是10个)
  2. 您需要在for(int i2 = 0; i2 < logicalSize-i2; i++)中增加i2,如下所示:for(int i2 = 0; i2 < logicalSize-i2; i2++)
  3. 您需要迭代到< 10而不是<= 10
  4. bubbleSort(arry1, 11)应为bubbleSort(arry1, 10)
  5. 您可能希望将for循环设置为(冒泡类型的不良版本):

     for (int i = 0; i < logicalSize; i++)
     {
         for(int i2 = 0; i2 < logicalSize; i2++)
         {
         }
     }
    

答案 1 :(得分: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;
}