/How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.
lt[6]={35,15,80,2,40,110};
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityAs mentioned in the comments, qsort
is a good option:
// qsort requires you to create a sort function
int sort_desc(const void *cmp1, const void *cmp2)
{
// Need to cast the void * to int *
int a = *((int *)cmp1);
int b = *((int *)cmp2);
// The comparison
return a > b ? -1 : (a < b ? 1 : 0);
// A simpler, probably faster way:
//return b - a;
}
void setup() {
// The array
int lt[6] = {35, 15, 80, 2, 40, 110};
// Number of items in the array
int lt_length = sizeof(lt) / sizeof(lt[0]);
// qsort - last parameter is a function pointer to the sort function
qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
// lt is now sorted
}
void loop()
{
}
man 3 qsort
? - Arduino programming is nothing more than C/C++ so you can use almost everything available there. Know your Language!