0

I have a sorting function inside class Array and wanted to achieve something like in python sort(reverse=True). I want to show user that they can pass this parameter because right now arr.bubble_sort(true); (check the code) dose not make much sense. I don't want lambda functions any idea how to achieve this.
Any other method also works because I know named parameters are not there in c++ probably.

PS: I have overloaded it by the way.
Regards,


// inside class Array

void bubble_sort(bool rev){   //overloaded bubble_sort
        if(rev){
            int i,j;
            for(i=0; i<size-1; i++){
                for(j=0; j<size-i-1; j++){
                    if(arr[j] < arr[j+1]){
                        std::swap(arr[j], arr[j+1]);
                    }
                }
            }
        }
        else{
            int i,j;
            for(i=0; i<size-1; i++){
                for(j=0; j<size-i-1; j++){
                    if(arr[j] > arr[j+1]){
                        std::swap(arr[j], arr[j+1]);
                    }
                }
            }
        }
    }


int main()
{
    int n;
    std::cin >> n;
    Array arr(n); // parameterized constructor initializing array of size n
    arr.bubble_sort(true);
    arr.print();

   return 0;
}
DK_bhai
  • 337
  • 3
  • 14

1 Answers1

2

Just provide this overloads:

void bubble_sort(std::function<bool<int, int>> cmp) {
    ...
                    if(cmp(arr[j], arr[j+1])){
                        std::swap(arr[j], arr[j+1]);
                    }
    ...
}

void bubble_sort(bool rev = false)
{
    bubble_sort(rev ? std::greater<int>{} : std::less<int>{});
}

Note that in c++ is static typed language, so overloads can be distinguish by argument type.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • If compiler is not smart enough, `cmp` will be a virtual call here. – Evg Oct 25 '20 at 07:50
  • yes, but he is a beginner and this detail is not important from his point of view. Introducing to him a templates would be an overkill. – Marek R Oct 25 '20 at 07:59