Search code examples
cswapbubble-sort

Swapping function c


I have to write a swap function for my bubble sort
That's what I've got:

void swap(int arr[], int size, int i, int j)
{
    int temp = *(arr+i);
    *(arr + i) = *(arr+j);
    *(arr+j) = temp;
}

When I'm trying to run I get the following errors:

warning C4013: 'swap' undefined; assuming extern returning int error C2371: 'swap' : redefinition; different basic types

When I do change the function to the type of int, it does work, any idea why?

I don't need a prototype because it's before the main function... do I?

Here's the whole code:

//BubbleSort

    void bubbleSort(int arr[], int size)
    {
        int i,j;
        for(i=0; i < size; i++)
        {
            for(j=i+1; j < size; j++)
            {
                if(*(arr+i) > *(arr+j))
                {
                     /*temp = *(arr+i);
                    *(arr + i) = *(arr + j);
                    *(arr + j) = temp;*/
                    swap(arr,i,j);
                }
            }
        }
    }
    void swap(int arr[], int i, int j)
    {
        int temp = *(arr+i);
        *(arr + i) = *(arr+j);
        *(arr+j) = temp;
    }
    void main()
    {
        int i, arr[] = {8,0,6,-22,9};
        bubbleSort(arr, sizeof(arr)/sizeof(int));
        for(i=0; i < sizeof(arr)/sizeof(int); i++)
        {
            printf("%d, ",*(arr+i));
        }
        printf("\n");
    }

Solution

  • Inside bubbleSort() you call a function named swap() but, at that point in the code, there is no function named swap() either defined or declared.

    Solution 1: move the defintion of swap() to before the definition of bubbleSort()
    Solution 2: specify the prototype of swap() before defining bubbleSort()