I have a 2D array with 2 rows and it has very large numbers (upto 10^9) in it. I am trying to sort the array based on 0th row.
Eg : I have an array : A[5][2]={{1,0},{3,1},{2,2},{6,3},{5,4}}
where 2nd row is index of the element.
Now I want to sort the array with retaining the original index.
After sorting A should be:
A[5][2]={{1,0},{2,2},{3,1},{5,4},{6,3}}
I did the following :
long long a[n+1][2];
for (long long i = 0; i < n; i++)
{
cin>>a[i][0];
a[i][1]=i;
}
qsort(a, n, sizeof a[0], compare);
And the compare function is :
int compare ( const void *pa,const void *pb )
{
int *a = (int*)pa;
int *b = (int*)pb;
if(a[0] == b[0])
return a[1] - b[1];
else
return a[0] - b[0];
}
It is working for small values of numbers. For large values,I am getting runtime error (SIGSEGV).
Can someone help in correcting the error ? Or is there a more efficient way to do this ?
Note : I had tried long long in compare function but it was giving conversion error.
error: invalid conversion from 'll (*)(const void*, const void*) {aka long long int (*)(const void*, const void*)}' to '__compar_fn_t {aka int (*)(const void*, const void*)}' [-fpermissive]
EDIT : Actually I could work away with only the index after sorting.