简体   繁体   English

冒泡排序奇怪的行为

[英]Bubble Sort weird behavior

I am trying to create a program that takes four values from the user, calculates it's factors then rearrange the factors in an ascending order.我正在尝试创建一个程序,该程序从用户那里获取四个值,计算它的因子,然后按升序重新排列这些因子。 I am using a bubble sort for the array of the factors but its not working as it should.我对因子数组使用冒泡排序,但它没有正常工作。 I tried tracing it on paper and it seems like everything is fine.我试着在纸上描绘它,似乎一切都很好。 Can you spot the logical error please?你能找出逻辑错误吗? I am testing with 4 3 9 1 .我正在测试 4 3 9 1 。 The factors are 3 2 3 1 and the arranged array should be 1233 instead it shows 1332因子是 3 2 3 1 并且排列的数组应该是 1233 而不是它显示 1332

#include <iostream>
using namespace std;

int FactorsOf ( int x )           //Calculates number of Factors of a number. If a negative number is given it returns -1
{
    int i ;
    int f = 0 ;
    if ( x > 0)
    {
    for (i=x ; i>0 ; i--)
    {
        if ( x % i == 0 )
        {
            f++;
        }
    }

}
    else { f = -1; }
    return f ; 
}
int MinOf ( int x , int y )      //Compares between two values and returns the smaller one
{
    int r;
    if (x<y)
    { r=x ; }
    else { r=y ;}
    return r ; 
}
int main ()                      // Gets 4 numbers from the user, calculates the number of factors per value, rearranges them ascendingly using an algorithem similar to bubble sort
{
    int a, b, c, d ;
    int A, B, C, D ;
    int i, j, k;
    cin>>a>>b>>c>>d;
    A = FactorsOf(a);
    B = FactorsOf(b);
    C = FactorsOf(c);
    D = FactorsOf(d);
    cout<<A<<B<<C<<D<< endl;
    int Factors[4] = { A , B , C , D } ;
  int temp; // So the swapped values dont get deleted out of the memory
for(i = 0; i < 4; i++)
{
      for(j = 1; j < 4; j++)
      {
               if(Factors[j] < Factors[i])
               {

                   temp = Factors[i];
                   Factors[i] = Factors[j];
                   Factors[j] = temp;
                }

    }
}
    cout<< "Array is:"<<endl ;
    for ( k=0 ; k<4 ; k++ )
    {cout<< Factors[k]<< endl ; }
}

The loops that sort the array should look at least like对数组进行排序的循环应该至少看起来像

for(i = 0; i < 4; i++)
{
      for(j = 1; j < 4; j++)
      {
               if(Factors[j] < Factors[j-1])
               {

                   temp = Factors[j-1];
                   Factors[j-1] = Factors[j];
                   Factors[j] = temp;
                }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM