Suppose I have the following struct:
struct Pair {
int x;
int y;
}
I want to sort the array by the first element in the pair, i.e. x and then by the second element so if we are given the following:
input: [(1,2), (1,0), (2,3), (1,4), (2,2)]
output: [(1,0), (1,2), (1,4), (2,2), (2,3)]
Right now I have two functions, one of them sorts the array by first element and the second one sorts it by second element but this is less efficient. How can I iterate through the array once and achieve the desired result?
void sort1(Pair ps[], int size) {
int i, j;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (ps[j].x > ps[j+1].x) {
Pair temp = ps[j+1];
ps[j+1] = ps[j];
ps[j] = temp;
}
}
}
}
void sort2(Pair ps[], int size) {
int i, j;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (ps[j].y > ps[j+1].y) {
Pair temp = ps[j+1];
ps[j+1] = ps[j];
ps[j] = temp;
}
}
}
}
Also, is there a quick way to do this using a built-in sorting function?