Jose Ishak
Jose Ishak

Reputation: 31

Sorting Numbers Descending Order with C++

I want to make a descending number sorter.

I want to ask about what's wrong with my code. Why does my code won't work properly if the 3rd variable b3 has the lowest value.

Example : b1 = 90, b2 = 60, b3 = 30 and the result is 90, 30, 30.

But if I inputted another number (as long as the 3rd variable is not the lowest value), my code work perfectly fine.

Example : b1 = 30 , b2 = 90 , b3 = 60 and the result is 90, 60, 30

Example : b1 = 30 , b2 = 60 , b3 = 90 and the result is 90, 60, 30

#include <iostream>
using namespace std;

int main(){

    int b1,b2,b3,h1,h2,h3;

    cout<<"Masukkan Bilangan 1: ";
    cin>>b1;
    cout<<"Masukkan Bilangan 2: ";
    cin>>b2;
    cout<<"Masukkan Bilangan 3: ";
    cin>>b3;

    if(b1 >= b2 && b1 >= b3){
        h1 = b1;
    }else if(b2 >= b1 && b2 >= b3){
        h1 = b2;
    }else{
        h1 = b3;
    }

    if(b2 >= b1 && b1 >= b3){
        h2 = b1;
    }else if(b2 >= b1 && b2 <= b3 ){
        h2 = b2;
    }
    else{
        h2 = b3;
    }

    if(b1 <= b2 && b1 <= b3){
        h3 = b1;
    }else if(b2 <= b1 && b2 <= b3){
        h3 = b2;
    }
    else{
        h3 = b3;
    }

    cout<<h1<<", ";
    cout<<h2<<", ";
    cout<<h3;
    return 0;
}

Upvotes: 0

Views: 1615

Answers (2)

SOORAJ M
SOORAJ M

Reputation: 21

The problem is in second nested if condition. If you put the values automatically the value of h2 will become 30. Instead try this..

if((b2 >= b1 && b1 >= b3) ||(b3 >= b1 && b1 >= b2)){
        h2 = b1;
    }else if((b2 >= b1 && b2 <= b3 )||(b2 >= b3 && b2 <= b1)){
        h2 = b2;
    }
    else{
        h2 = b3;
    }

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182893

The only code that sets h2 to b1 is this code:

if(b2 >= b1 && b1 >= b3){
    h2 = b1;

But h2 should be set to b1 if b1 is between b2 and b3. And that can be true two different ways, and you only test for one of them.

For example, 10 is between 5 and 30. But 10 is also between 30 and 5!

Trying to cover every possible case is not a sensible way to sort more than two numbers. Use a sensible sorting algorithm.

Upvotes: 1

Related Questions