I have an array of 16 numbers that i need to sort in descending order, I tried sorting them this way but can’t seem to make it work.
Note : I have to program an algorithm so i can’t use any special functions 🙁
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, temp1, temp2;
int string2[16] = { 0, 4, 2, 5, 1, 5, 6, 2, 6, 89, 21, 32, 31, 5, 32, 12 };
_Bool check = 1;
while (check) {
temp1 = string2[i];
temp2 = string2[i + 1];
if (temp1 < temp2) {
string2[i + 1] = temp1;
string2[i] = temp2;
i = 0;
} else {
i++;
if (i = 15) {
check = !check;
}
}
}
return 0;
}
I realize that this is pretty basic stuff for most of you but any insight is much appreciated!
>Solution :
There’re a few problems:
_Boolis a strange thing to use in C++ (maybe this question intended for C?)- You didn’t initialize
i. This is called an undefined behavior. This may or may not work, depends on the computer, but it’s never good to have something like that in your program. (i=15)is an assignment. Usei==15for comparison, as==is the comparison operator for "equal to".
Reviewed code:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main()
{
int i = 0,temp1,temp2; //i should be initialized
int string2[16] = {0,4,2,5,1,5,6,2,6,89,21,32,31,5,32,12};
bool check=1;
while(check)
{
temp1=string2[i];
temp2=string2[i+1];
if(temp1<temp2)
{
string2[i+1]=temp1;
string2[i]=temp2;
i=0;
}
else
{
i++;
if(i==15) { check=!check; } // = -> ==
}
}
//if this is intended for C, you can ignore this bit, or use printf
for (int i = 0; i < 16; i++) { std::cout << string2[i] << " ";}
}
Output: 89 32 32 31 21 12 6 6 5 5 5 4 2 2 1 0
A few more aesthetic notes:
- If you use indentation (tabs and/or space), be consistent. Others may have a hard time understanding your code, although it doesn’t matter when the program compile (to anyone questioning, this is before he re-indented the code).
string2is an irregular name of anintarray. Again, it could cause confusion. A reading : https://1c-dn.com/library/rules_of_naming_variables/