0

I'm working with Arduino and getting some strange errors. qsorting is not sorting correctly.

//using this libraries
#include <ESP8266WiFi.h>
#include <inttypes.h>

//the red struct is

typedef struct {
    int32_t rssi;
    int id;
} red;

//Here is my compare function
int compare (const void * a, const void * b)
{
  yield();
  red *redA = (red *)a;
  red *redB = (red *)b;
  //Serial.printf("redA->rssi: %d, redB->rssi: %d\n",redA->rssi,redB->rssi);
  //Serial.flush();

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);
  //return ( redB->rssi - redA->rssi );
}


void showNetworks(){
  int n = WiFi.scanNetworks(false,false);
  red listOfRedes[n];


  for (int i = 0; i < n; i++) // ...initialize it
  { 
    yield();
    listOfRedes[i].rssi = WiFi.RSSI(i);
    listOfRedes[i].id = i; 
    Serial.printf("%d: RSSI%d\n", i, listOfRedes[i].rssi);
    Serial.flush();
  }
  Serial.printf("salio\n");
  Serial.flush();
  qsort (listOfRedes, n, sizeof(red), compare);
  Serial.printf("ordeno\n");
  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    Serial.printf("%d: RSSI:%" PRId32 "\n", listOfRedes[i].id, listOfRedes[i].rssi);
  }
}

and this is the output i get

0: RSSI-69
1: RSSI-65
2: RSSI-72
3: RSSI-50
4: RSSI-60
5: RSSI-87
6: RSSI-87
7: RSSI-79
8: RSSI-80
9: RSSI-88
10: RSSI-74
11: RSSI-77
12: RSSI-78
13: RSSI-83
14: RSSI-79
15: RSSI-60
16: RSSI-85
17: RSSI-86
18: RSSI-66
19: RSSI-88
20: RSSI-80
21: RSSI-74
22: RSSI-81
23: RSSI-87
salio
ordeno
4: RSSI:-60
1: RSSI:-65
0: RSSI:-69
3: RSSI:-50
18: RSSI:-66
15: RSSI:-60
2: RSSI:-72
10: RSSI:-74
11: RSSI:-77
21: RSSI:-74
19: RSSI:-88
20: RSSI:-80
22: RSSI:-81
23: RSSI:-87
12: RSSI:-78
5: RSSI:-87
6: RSSI:-87
7: RSSI:-79
8: RSSI:-80
9: RSSI:-88
13: RSSI:-83
14: RSSI:-79
16: RSSI:-85
17: RSSI:-86

As you can see the sorting is not OK and I don't get why. Thank you in advance and sorry for my poor English.

  • Thanks st2000 i did not know how to formatt it – llocani Jan 25 at 15:19
  • Don't use qsort, use std::sort. – tttapa Jan 25 at 16:38
1

In your program there is this line of code:

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);

Which appears to return a 1 if A is greater then B other wise it will return a 0. This code can not tell the difference between A < B and A == B. Consider altering this line of code to allow returning 1 for A > B, 0 for A == B and -1 for A < B:

  return redA->rssi > redB->rssi ? 1 : (redA->rssi < redB->rssi ? -1 : 0);
| improve this answer | |
  • can't belive i did that.... like.... for hours..... thank you men, i'm an idiot.... – llocani Jan 25 at 18:54
  • I didn't see it for a while either. Glad I could help. – st2000 Jan 25 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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