'can you help me to fix this code about bubble sort? [closed]

i am newbie, i don't know how to fix it? i don't know how to call function void bubblesort

 #include<iostream>

using namespace std;

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

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


Solution 1:[1]

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]));

Solution 2:[2]

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

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jloh
Solution 2
Solution 3 Caleth