3

/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};
9
  • 1
    Have you tried man 3 qsort? - Arduino programming is nothing more than C/C++ so you can use almost everything available there. Know your Language!
    – Kwasmich
    May 10, 2017 at 13:02
  • 1
    Online version: qsort() manual from avr-libc. May 10, 2017 at 13:04
  • 2
    @Kwasmich no i am new in this field, please help me. May 10, 2017 at 13:04
  • 4
    I'm voting to close this question as off-topic because it's a programming question. May 10, 2017 at 13:35
  • 1
    Stack Overflow is a much better match for your question than this site. May 10, 2017 at 13:39

1 Answer 1

7

As 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()
{
}
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.