Search code examples
c++comparebubble-sort

Compare function in bubble sort c++


Hi i need to implement compare function inside bubble sort algorithm but i have no idea how to do this.

Compare function:

int compareNumbers(const void *a, const void  *b)
{
    object *A = (object *)a;
    object *B = (object *)b;
    if(A->number > B->number)
        return 1;
    else if(A->number < B->number)
        return -1;
    else
        return 0;
}

and bubble sort:

void bubble_sort(object tab[],int size_tab)
{
object temp;
for(int i=1; i<size_tab; i++)
{
    for(int j=0; j<size_tab - i; j++)
    {
        if(tab[j].number > tab[j+1].number)
        {               
            temp = tab[j];
            tab[j] = tab[j+1];
            tab[j+1] = temp;
        }

    }   
}

I'm not sure if when I want to implement bubble sort, the line:

if(tab[j].number > tab[j+1].number)

should disappear.


Solution

  • Try something like

    bool compareNumbers(const void* a, const void* b) {
        object* A = (object*) a;
        object* B = (object*) b;
        if (A->number <= B->number) {
            return true;
        } else {
            return false;
        }
    }
    

    Then change bubbleSort params in order to look like

    void bubbleSort(object tab[], int size_tab, 
                    bool(comparator*)(const void*, const void*))
    

    Now you can pass the pointer to compareNumbers function as third argument of bubbleSort function:

    bubbleSort(a, n, &compareNumbers);
    

    and use it in bubbleSort's implemetntation:

    void bubbleSort(object tab[], int size_tab, 
                    bool(comparator*)(const void*, const void*)) {
        object temp;
        for (int i = 1; i < size_tab; i++) {
            for (int j = 0; j < size_tab - i; j++) {
                if (comparator(tab + j, tab + j + 1)) {               
                    temp = tab[j];
                    tab[j] = tab[j+1];
                    tab[j+1] = temp;
                }
            }
        }
    }