2

/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};
  • 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 '17 at 13:02
  • 1
    Online version: qsort() manual from avr-libc. – Edgar Bonet May 10 '17 at 13:04
  • 2
    @Kwasmich no i am new in this field, please help me. – Hafeez Ahmad Fii Zue May 10 '17 at 13:04
  • 4
    I'm voting to close this question as off-topic because it's a programming question. – Enric Blanco May 10 '17 at 13:35
  • 1
    Stack Overflow is a much better match for your question than this site. – Enric Blanco May 10 '17 at 13:39
5

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()
{
}
| improve this answer | |

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