fork(2) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct rank_pair {
  5. double val;
  6. size_t ind;
  7. };
  8.  
  9. int cmp_rank_pair(const void* a, const void* b) {
  10. struct rank_pair *lhs = (struct rank_pair*)a;
  11. struct rank_pair *rhs = (struct rank_pair*)b;
  12. return lhs->val < rhs->val ? -1 : (lhs->val > rhs->val ? 1 : 0);
  13. }
  14.  
  15. void rank(double a[], int r[], size_t n) {
  16. struct rank_pair *tmp = malloc(n*sizeof(struct rank_pair));
  17. for (int i = 0 ; i != n ; i++) {
  18. tmp[i].val = a[i];
  19. tmp[i].ind = i;
  20. }
  21. qsort(tmp, n, sizeof(struct rank_pair), cmp_rank_pair);
  22. for (int i = 0 ; i != n ; i++) {
  23. r[tmp[i].ind] = i+1;
  24. }
  25. free(tmp);
  26. }
  27.  
  28. int main(void) {
  29. const size_t N = 10;
  30. double a[] = {0.25, 0.54, 0.38, 0.32, 0.49, 0.06, 0.41, 0.21, 0.98, 0.23};
  31. int r[N];
  32. rank(a, r, N);
  33. for (int i = 0 ; i != N ; i++) {
  34. printf("%d\n", r[i]);
  35. }
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
4
9
6
5
8
1
7
2
10
3