您能帮我解决有关气泡排序的代码吗?

发布于 2025-01-29 03:40:30 字数 1490 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北方的巷 2025-02-05 03:40:30

正确调用函数传递a及其大小的正确语法将如下所示。当将a传递给该功能时,无需让Square Brackets []

此外,要将数组的大小作为第二个参数,您可以使用std :: size,它可以使用c ++ 17使用,也可以使用Expression a / sizeof a [0] < / code>的尺寸也如下所示。

//----------v---------------->no need for the square brackets [] 
bubbleSort(a, std::size(a)); //use std::size(a) with C++17

bubbleSort(a, sizeof a / sizeof a[0]); //works with all C++ versions

工作demo

The correct syntax to call the function passing a and its size would be as shown below. There is no need to have the square brackets [] when passing a to the function.

Additionally, for passing the size of the array as the second argument, you can either use std::size which is available with C++17 or use the expression sizeof a / sizeof a[0] also shown below.

//----------v---------------->no need for the square brackets [] 
bubbleSort(a, std::size(a)); //use std::size(a) with C++17

Or

bubbleSort(a, sizeof a / sizeof a[0]); //works with all C++ versions

Working demo

猫七 2025-02-05 03:40:30

当您将数组作为参数传递到函数中时,您只需将其传递,就好像它是变量一样。在这种情况下,只有a就可以做到。这是因为 arrays”> arrays“ decay'to pointers so 代码>是您数组的“指针”。

此外,我建议除sizeof(a [0]) sizeof函数返回字节中的大小

bubbleSort(a, sizeof(a)/sizeof(a[0]));

When you pass an array as an argument into a function, you simply pass it as if it were a variable. In this case, simply just a would do. This is because arrays "decay" into pointers so a is a "pointer" to your array.

In addition, I recommend dividing by the sizeof(a[0]) to get the full length as the sizeof function returns the size in bytes

bubbleSort(a, sizeof(a)/sizeof(a[0]));
狠疯拽 2025-02-05 03:40:30

您可以传递对数组的引用,而不是通过指针和长度。

您也不需要[]即可为a;

template<size_t n>
void bubbleSort(int (&a)[n])
{
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[j - 1])
                std::swap(a[j], a[j - 1]);
}

int main()
{
    int a[]={1,4,7,2,6,5,3,9,8,10};
    bubbleSort(a);
    for (size_t i=0;i<10;i++)
    {
        std::cout << a[i];
    }
}

Rather than pass a pointer and a length, you could pass a reference to the array.

You also don't need [] to name a;

template<size_t n>
void bubbleSort(int (&a)[n])
{
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[j - 1])
                std::swap(a[j], a[j - 1]);
}

int main()
{
    int a[]={1,4,7,2,6,5,3,9,8,10};
    bubbleSort(a);
    for (size_t i=0;i<10;i++)
    {
        std::cout << a[i];
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文