Home > Back-end >  Sorting numbers of an array in descending order
Sorting numbers of an array in descending order

Time:11-17

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!

CodePudding user response:

There're a few problems:

  1. _Bool is a strange thing to use in C (maybe this question intended for C?)
  2. 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.
  3. (i=15) is an assignment. Use i==15 for 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).
  • string2 is an irregular name of an int array. Again, it could cause confusion. A reading : https://1c-dn.com/library/rules_of_naming_variables/

CodePudding user response:

You could also use std::sort with std::greater<int>() parameter: std::sort(std::begin(string2), std::end(string2), std::greater<int>()); don't invent a bicycle except you need to learn something or you know the way how to optimize your case.

  • Related