I am sorting a two dimensional array a[n][2], with respect to a[i][0],a[i+1][0] breaking ties with non-decreasing a[i][1],a[i+1][1]. qsort is working fine with integer array but not with long long array.
Integer array code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
int cmpfunc(const void* a, const void* b)
{
int x = ((int*)a)[0] - ((int*)b)[0];
if (x != 0) {
return x;
}
return ((int*)a)[1] - ((int*)b)[1];
}
int main(int argc, char const* argv[])
{
int n, i, j;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i = i + 1) {
scanf("%d %d", &a[i][0], &a[i][1]);
}
qsort(a, n, sizeof(a[0]), cmpfunc);
for (i = 0; i < n; i = i + 1) {
printf("%d %d\n", a[i][0], a[i][1]);
}
return 0;
}
long long array code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
int cmpfunc(const void* a, const void* b)
{
int x = ((int*)a)[0] - ((int*)b)[0];
if (x != 0) {
return x;
}
return ((int*)a)[1] - ((int*)b)[1];
}
int main(int argc, char const* argv[])
{
int n, i, j;
scanf("%d", &n);
long long a[n][2];
for (i = 0; i < n; i = i + 1) {
scanf("%I64d %I64d", &a[i][0], &a[i][1]);
}
qsort(a, n, sizeof(a[0]), cmpfunc);
for (i = 0; i < n; i = i + 1) {
printf("%I64d %I64d\n", a[i][0], a[i][1]);
}
return 0;
}
Input:
5
4 3
4 2
4 1
4 1
4 1
Output for first code:
4 1
4 1
4 1
4 2
4 3
Output for second code:
4 2
4 1
4 1
4 1
4 3