We are trying to sort three numbers using If-Else only and no sorting algorithm.
There are couple of possibilities but the easiest one with minimum comparison is presented here.
C++ Code
There are couple of possibilities but the easiest one with minimum comparison is presented here.
C++ Code
#include <iostream>
using namespace std;
void smallSort(int &a, int &b, int &c) {
if(a > b) { // if a is greater than b, swap them
int temp = a;
a = b;
b = temp;
}
if(a > c) { // if a is greater than c, swap them
int temp = a;
a = c;
c = temp;
}
// Now A is the smallest. We just need to compare B and C and swap if needed.
if(b > c) {
int temp = b;
b = c;
c = temp;
}
}
int main(){
int a = 14;
int b = -90;
int c = 2;
smallSort(a, b, c);
cout << a << ", " << b << ", " << c << endl;
return 0;
}
No comments:
Post a Comment