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); }

4
  • In which language you are looking for the code? OR You are just looking for quick sort algorithm? Commented Jan 25, 2013 at 14:40
  • How exactly is the result calculated? Can you show us how that resulting array is constructed from the two inputs? Commented Jan 25, 2013 at 14:41
  • @RavindraGullapalli i am looking for syntex in c. Commented Jan 25, 2013 at 15:19
  • Does this answer your question? using qsort to sort two arrays simultaneously? Commented Jun 16, 2021 at 5:12

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

that comparison function may overflow, see stackoverflow.com/a/27284248/3163618
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.