b83503104 said:
In matlab, the sort function returns two things:
[a,b]=sort([5, 8, 7])
a = 5 7 8
b = 1 3 2
where a is the sorted result, and b is the corresponding index.
Is there C or C++ code available to achieve this?
Thanks
Declare an array of pointers that point to the address of each
element of the int array. Using qsort, sort the array of pointers
and use pointer math to calculate the corresponding index.
#include <stdio.h>
#include <stdlib.h>
#define ARRSZ 16
int cmp(const void *v1, const void *v2)
{
const int i1 = **(const int **)v1;
const int i2 = **(const int **)v2;
return i1<i2?-1
i1>i2);
}
int main(void)
{
int array[ARRSZ] = {5,7,3,8,2,5,9,1,55,25,66,44,42,4,10,11};
int *parray[ARRSZ],i;
for(i = 0; i < ARRSZ;i++) parray
= &array;
qsort(parray,ARRSZ, sizeof *parray,cmp);
puts("Sorting the values:");
for(i = 0;i < ARRSZ;i++) printf("%d ",array);
puts("\n");
for(i = 0;i < ARRSZ;i++)
printf("value: %-6d position: %d\n",*parray,
(parray-array)+1);
return 0;
}