忽略用于气泡排序的 if 语句

Ignoring if statement used for bubble sort

本文关键字:if 语句 排序 气泡 用于      更新时间:2023-10-16
    srand(time(NULL));
    int rand = Randomiser();
    temp = placement[49];
    //Loops variables in array to produce scrolling
    for(i = 0;i<50; i++)
    {
        placement[49-i] = placement[49-(i+1)];
    }
    if(temp==2)
    {
        temp=temp2;
    }
    if(rand>90)
    {
      temp2=temp;
      temp=2;
    }
    placement[0]=temp;

所以我把它改成这样,我的值现在入了,但问题是这个值一次插入了大约 12 次。所以 6 个展示位置 = 2

下面的代码是你真正想要的吗?在此示例中,i环旋转环。请注意,通常您不会移动所有元素,而只是通过(start+i)%size移动环的起点和地址。

请注意,对于排序,您有std::sort它比气泡排序更有效。

#include <cstdlib>
#include <vector>
#include <iostream>
int Randomiser() {
    return rand() % 101;
}
int main() {
    srand(time(NULL));
    std::vector<int> placement(50,0);
    for(int j = 0; j<100; j++)
    {
        int temp, temp2;
        int rand = Randomiser();
        bool controlRod=true;
        if(rand<80)
        {
            temp2 = placement[49];
            placement[49]=2;
        } 
        temp = placement[49];
        for(int i = 0; i<50; i++)
        {
            placement[49-i] = placement[49-(i+1)];
        }
        placement[0] = temp;
    }
    std::cout << "nThis time in placement[0]: " << placement[0] << "n";
}
/**
     Local Variables:
     compile-command: "g++ -g test.cc -o test.exe; ./test.exe"
     End:
*/

它不会忽略 if 语句,它只是在内部for循环的第一次迭代后计算为 false。您的代码:

for( ... )
{
    bool controlRod = true;
    for( ... )
    {
        if( ... && controlRod == true )
        {
               // ...
        }
        // ...
        controlRod = false; // <-- set to false so condition is always false
    }
}

如果我们展开内部循环,我们会得到如下内容:

for( ... )
{
    bool controlRod = true;
    // iteration 1 ----------------------------------------------------
    if( ... && controlRod == true )
    {
        // ...
    }
    // ...
    controlRod = false; // <-- set to false so condition is always false
    // iteration 2 ------------------------------------------------------
    if( ... && controlRod == true ) // controlRod was set to false, 
                                    // so this will never be true
    {
        // ...
    }
    // ...
    controlRod = false; // <-- set to false so condition is always false
    // iteration 3 --------------------------------------------------
    if( ... && controlRod == true ) // controlRod was set to false, 
                                    // so this will never be true
    {
        // ...
    }
    // ...
    controlRod = false; // <-- set to false so condition is always false
    // more iterations...
}