c++ - 冒泡排序奇怪的行为

标签 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 ; }
}

最佳答案

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

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;
                }

    }
}

关于c++ - 冒泡排序奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285549/

相关文章:

c# - 按降序自然排序字符串列表 C#

c++ - 如何对多数据 vector 进行排序?

java - 如何根据日期对HashMap进行排序?

c++ - QOpenGLVertexArrayObject 的使用

c++ - 向后移动下一个节点函数

java - 为什么 array.sorts 对父数组进行排序?

使用 Dojo Dgrid 默认(加载时)对列进行排序

c++ - 将 const QByteArray 传递给重载函数

c++ - 什么是 C 中指向 'array of characters' 的指针?

c++ - 窗口 HTTP IO 完成端口