The function accepts an array of structure instances and the number of instances, and sorts this array by 2 fields ( nomer and sname ) in descending order, but the sorting does not occur, all the time the same fields are passed to the condition, what is the error?

 int SelectSort(contact *buf, int NumEl) { for (int i = 0; i < NumEl - 1; i++) { int i_min = i; for (int j = i + 1; j < NumEl; j++) { if (strncmp(buf[i_min].nomer, buf[j].nomer, 2) >= 0) { if (strcmp(buf[i_min].sname, buf[j].sname) >= 0) i_min = j; } } if (i_min != i) { swap(buf[i], buf[i_min]); } } return 0; } 
  • check the comparison logic. You think that the element is smaller, if it has both a number and a name less. So conceived? - pavel
  • If I sort by number and within the same numbers sort alphabetically, shouldn't such a comparison be? - Clarence
  • not. You compare both parameters at once. - pavel

1 answer 1

Use when sorting ONE comparison function.

In your case, this is something like

 int ContactCmp(const contact& a, const contact& b) { int res = strncmp(a.nomer, b.nomer, 2); if (res) return res; return strcmp(a.sname, b.sname); } 

However, it seems to me that I already wrote this to you, no?

  • that is, in a cycle by j, if the function returns> 0 then i_min = j; I understood correctly? - Clarence
  • one
    If this function returns> 0, then a> b. If less, then less. - Harry