C++ - Would like some help on this sorting code -


#include <iostream> #include <cstdio> using namespace std;  int val1; int val2; int val3; int sortarray[3];  int main(){      printf("enter 3 integer values.\n");     printf("please enter integer 1: ");     cin >> val1;     printf("please enter integer 2: ");     cin >> val2;     printf("please enter integer 3: ");     cin >> val3;       //checks val1 status     if (val1 > val2, val3) {         sortarray[1] = val1;     }     if (val1 > val2, val1 < val3){         sortarray[1] = val3;         sortarray[2] = val1;         sortarray[3] = val2;     }     if (val1 > val3, val1 < val2){         sortarray[1] = val2;         sortarray[2] = val1;         sortarray[3] = val3;     }      //checks val2 status     if (val2 > val1, val3){         sortarray[1] = val2;     }     if (val2 > val1, val2 < val3){         sortarray[1] = val3;         sortarray[2] = val2;         sortarray[3] = val1;     }     if (val2 > val3, val2 < val1){         sortarray[1] = val1;         sortarray[2] = val2;         sortarray[3] = val3;     }      //checks val3 status     if (val3 > val1, val2){         sortarray[1] = val3;     }     if (val3 > val1, val3 < val2){         sortarray[1] = val2;         sortarray[2] = val3;         sortarray[3] = val1;     }     if (val3 > val2, val3 < val1){         sortarray[1] = val1;         sortarray[2] = val3;         sortarray[3] = val2;     }      printf("values sorted are: %d, %d, %d", sortarray[1], sortarray[2], sortarray[3]); } 

this program works when values input in following orders:

1, 2, 3

1, 3, 2

3, 1, 2

but not work with:

2, 3, 1

3, 2, 1

2, 1, 3

any ideas im doing wrong here? id love has been irking me while now.

i think might little confused on how if statements work in c++. if want multiple conditions have true in order execute code, need use &&, not comma. commas different, execute several statements use last 1 evaluation. read article, particularly sections titled "logical operators" , "comma operator".

in summary, every 1 of if statements replace comma &&. that, however, not address fact sorting algorithm not scalable, since you've hardcoded every possible scenario. real sorting algorithms.


Comments