C++ 气泡数组赋值 - 添加标记以显示变化

C++ Bubble Array Assignment - Adding markers to show change

我在大学期间接到了一项作业,该作业的一部分是使用冒泡排序向数组中移动的元素添加星号 (*)。我尝试了一些不同的方法来尝试让它工作,但最终没有任何效果。以下是我的具体要求:

"5. Create an extra array of bools (one for each element in the array), so that if a pair of elements are changed round in a cycle, the bools change to true, and those elements are displayed surrounded by stars (*) to show that the change has occurred. Then reset the array of bools to false, ready for the next cycle. REMEMBER you need to TEST the value of the Boolean in order to decide whether to output the asterisks or not"

这是我的代码:

int main()
{
    double Numbers[NMAX] = {31.2, 29.7, 53.5, 69.0, 23.7, 71.8, 49.3, 52.9, 51.3, 57.1};
    bool change[NMAX] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    // note this top counter, i, counts down
    int counter = 0;
    for (int i=NMAX-1; i>0; i--)
    {
        //and this counter, j, only goes as far as the current i value 
        // it means it doesn't go over the elements that have already 'bubbled up' to the end of the array
        for (int j=0; j<i; j++)
        {
            double temp;
            // Compare 2 values - increment a counter here
            counter++;

            if (Numbers[j]>Numbers[j+1])
            {
                temp = Numbers[j];
                Numbers[j]= Numbers[j+1];
                Numbers[j+1]= temp;
                cout << "Array: " << endl;
                change[j] = true;
                change[j + 1] = true;

                for (int i = 0; i < 10; i++)
                {
                    cout << Numbers[i] << ", ";
                }
            }
        }
    }

    // display the sorted array:
    cout << endl;
    cout<<"ARRAY CONTENTS SORTED, IMPLEMENTATION 1 "<<endl;
    for (int i=0; i<NMAX; i++)
    {
        cout<<Numbers[i]<<endl;
    }
    //Display the values of the counter after the whole sort
    return 0;
}

我是 Whosebug 的新手,如果我的问题格式不当,我深表歉意。

我不明白为什么需要额外的 bool 数组,如果 你还记得你输出Numbers时交换了jj+1。我会简单地写:

for (int n = 0; n < NMAX; ++n)
{
    if (n == j + 1 || n == j) 
        cout << '*' << Numbers[n] << "*, ";
    else
        cout << Numbers[n] << ", ";
}

但是,如果有这样的要求,那么请遵循它并尝试通过检查您的 bool 数组的内容来达到相同的效果。还请记住将其重置为 false 所需的。