Simply switching the parameters in the recursive call doesn't actually swap the values of the variables in the caller, or anywhere else. There's no (sensible) way to write this recursively because swapping isn't a recursive procedure. Recursion is used when you're traversing a data structure with multiple elements, like an array or a tree, or you're manipulating numbers repeatedly over time, as in a Fibonacci sequence.
But here, there's no repeated decision to be had. All it is is "swap if a > b
, otherwise don't", which is a simple if
, plus one of the normal swapping approaches you described:
#include <iostream>
void swap_if_greater(int &a, int &b) {
if (a > b) {
std::swap(a, b);
}
}
int main() {
int x = 10;
int y = 8;
swap_if_greater(x, y);
std::cout << x << ' ' << y; // => 8 10
}
Note that I've renamed the function. swap
implies an unconditional swap, but that's not what the function does. The function ensures the lower value will be in the first argument, so it's been renamed to swap_if_greater
to reflect that. If you do want an unconditional swap, use std::swap
.