fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Цвета.
  5. int a[10] = { 5, 3, 1, 0, 6, 9, 8, 2, 7, 4 };
  6.  
  7. // Веса.
  8. int b[10] = { 30, 97, 72, 31, 89, 28, 56, 83, 99, 66 };
  9.  
  10. struct bottle { int weight; int color; };
  11.  
  12. static int compare_structures(const void *e1, const void *e2)
  13. {
  14. // Преобразовываем в указатели на склянки.
  15. const struct bottle *b1 = e1;
  16. const struct bottle *b2 = e2;
  17.  
  18. // Сравниваем.
  19. // return (b1->weight < b2->weight) ? -1 : (b1->weight > b2->weight) ? 1 : 0;
  20. return b1->weight - b2->weight;
  21. }
  22.  
  23. static void using_structures(void)
  24. {
  25. // Создаем и заполняем массив структур. В реальности этого делать не нужно,
  26. // нужно сразу хранить в таком виде.
  27.  
  28. struct bottle bottles[10];
  29.  
  30. for (size_t i = 0; i < 10; i++)
  31. {
  32. bottles[i].color = a[i];
  33. bottles[i].weight = b[i];
  34. }
  35.  
  36. // Сортируем.
  37. qsort(bottles, 10, sizeof(bottles[0]), compare_structures);
  38.  
  39. // Выводим.
  40. for (size_t i = 0; i < 10; i++)
  41. printf("Bottle: color %i, weight %i\n", bottles[i].color, bottles[i].weight);
  42. }
  43.  
  44. static int compare_with_indices(const void *e1, const void *e2)
  45. {
  46. // Достаем индексы.
  47. size_t i1 = *(const size_t *) e1;
  48. size_t i2 = *(const size_t *) e2;
  49.  
  50. // Сравниваем.
  51. // return (b[i1] < b[i2]) ? -1 : (b[i1] > b[i2]) ? 1 : 0;
  52. return b[i1] - b[i2];
  53. }
  54.  
  55. static void using_indices(void)
  56. {
  57. // Наша сортированная вьюшка с индексами.
  58. int sorted_by_weight[10];
  59.  
  60. // Заполняем.
  61. for (size_t i = 0; i < 10; i++)
  62. sorted_by_weight[i] = i;
  63.  
  64. // Сортируем.
  65. qsort(sorted_by_weight, 10, sizeof(sorted_by_weight[0]), compare_with_indices);
  66.  
  67. // Выводим.
  68. for (size_t i = 0; i < 10; i++)
  69. {
  70. size_t j = sorted_by_weight[i];
  71. printf("Bottle %zu: color %i, weight %i\n", j, a[j], b[j]);
  72. }
  73. }
  74.  
  75. int main(void)
  76. {
  77. printf("Using structures:\n");
  78. using_structures();
  79. printf("Using indices:\n");
  80. using_indices();
  81. return 0;
  82. }
  83.  
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
Using structures:
Bottle: color 9, weight 28
Bottle: color 5, weight 30
Bottle: color 0, weight 31
Bottle: color 8, weight 56
Bottle: color 4, weight 66
Bottle: color 1, weight 72
Bottle: color 2, weight 83
Bottle: color 6, weight 89
Bottle: color 3, weight 97
Bottle: color 7, weight 99
Using indices:
Bottle 5: color 9, weight 28
Bottle 0: color 5, weight 30
Bottle 3: color 0, weight 31
Bottle 6: color 8, weight 56
Bottle 9: color 4, weight 66
Bottle 2: color 1, weight 72
Bottle 7: color 2, weight 83
Bottle 4: color 6, weight 89
Bottle 1: color 3, weight 97
Bottle 8: color 7, weight 99