Search code examples
c++bubble-sort

can you help me to fix this code about bubble sort?


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

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