Sorting an array based on elements of another array in C ++

my problem is the following (this is a simple example to show the problem):

I have:

int* array1;
double* array2. 

array1=new int[10];
array2=new double[10];
array1=filledWithIntegers(random);
array2=filledWithDoubles(random);

// Here I want to sort array1 based on the values โ€‹โ€‹of array2. I am trying to use the qsort function for stdlib. qsort (array1,6, sizeof (int), comparison);

The point is how to make a comparison function for the array order1 based on the array.

It is impossible to use std library data structures; this must be done directly in the pointers of the array.

Thank.

+5
source share
3 answers

array1 array2[index] , array1 , .

:

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

int array1[] = {1, 7, 3, 9, 5};
double array2[] = {1.1, 7.7, 3.3, 9.9, 5.5};

int compare (const void * a, const void * b) {
    double diff = array2[*(int*)a] - array2[*(int*)b];
    return  (0 < diff) - (diff < 0);
}

int main(void) {
    int perm[5], i;
    int res[5];
    for (i = 0 ; i != 5 ; i++) {
        perm[i] = i;
    }
    qsort (perm, 5, sizeof(int), compare);
    for (i = 0 ; i != 5 ; i++) {
        res[i] = array1[perm[i]];
    }
    for (i = 0 ; i != 5 ; i++) {
        printf("%d\n", res[i]);
    }
    return 0;
}
+5

. , .

:

bool compare(const pair<int,double>& t1, const pair<int,double>& t2){
    return (t1.second < t2.second);
}
+2

( , ):

int compare(const void *a, const void *b)
{
    unsigned int i = (const int*)a - array1;
    unsigned int j = (const int*)b - array1;
    if(array2[i] < array2[j])
        return -1;
    if(array2[i] > array2[j])
        return 1;
    return 0;
}

, , .

In any case, I would question the use qsort, since your question is tagged with C ++. Although it std::sorthas the same problem, you can achieve much more generality / abstraction with a comparison functor that encapsulates dependent arrays.

+1
source

All Articles