0

I want to use qsort() to sort array a with respect to b. Can you give me the function?

a={0,1,2,3,4} b={3,4,5,1,2}

answer must be {3,4,0,1,2}

Please give me the code of function.

like : int compare (const void *a,const void *b) { return(*(char *)a-*(char *)b); }

BenMorel
  • 34,448
  • 50
  • 182
  • 322
in3o
  • 321
  • 2
  • 3
  • 14

2 Answers2

4

This isn't possible the way you currently have it because qsort() takes in one array and compares elements of the array against each other. You would need to create a single array of a struct containing both values, like so:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    int a;
    int b;
} c_type;

int
compare(const void *a, 
        const void *b) {
    return ((c_type *)a)->b - ((c_type *)b)->b;
}

int
main(int argc,
     char *argv[])
{
    int i = 0;
    c_type array[] = {{0, 3}, {1, 4}, {2, 5}, {3, 1}, {4, 2}};

    qsort(array, sizeof array / sizeof(*array), sizeof(*array), compare);

    for ( i = 0; i < sizeof array / sizeof(*array); i++ ) {
       printf("%d\t", array[i].a);
    }
    printf("\n");

    return 0;
}
SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17
  • that comparison function may overflow, see https://stackoverflow.com/a/27284248/3163618 – qwr Jun 16 '21 at 05:13
0

You would need a mechanism to inform the compare function what to compare to rather than the vanilla implementation of comparing with values stored in the addresses passed to it. This can be achieved with a static (global) storage:

#include<stdlib.h>

int *Array= NULL;
void SetArray(int *const array)
{
  Array= array;
}

int basecompare(const void *a, const void *b)
{
  return Array[*((int *) a)]- Array[*((int *) b)];
}
int main(int argc, char *argv[])
{
  int a[]= { 0, 1, 2, 3, 4 };
  int b[]= { 3, 4, 5, 1, 2 };
  size_t len= sizeof(a)/ sizeof(a[0]);

  SetArray(b);

  qsort(a, len, sizeof(int), basecompare);

  return 0;
}