冒泡排序奇怪的行为

时间:2016-03-29 13:20:42

标签: c++ sorting

我正在尝试创建一个程序,该程序从用户获取四个值,计算它的因子然后按升序重新排列因子。我正在对因子数组使用冒泡排序,但它不能正常工作。我试着在纸上追踪它,似乎一切都很好。你能发现逻辑错误吗? 我正在测试4 3 9 1。因子是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 ; }
}

1 个答案:

答案 0 :(得分:1)

对数组进行排序的循环应该至少看起来像

{{1}}