Skip to content

Instantly share code, notes, and snippets.

@AmirHosein-Gharaati
Last active June 11, 2022 19:42
Show Gist options
  • Save AmirHosein-Gharaati/f0cbad2add3d9b491f4661e13c1db47d to your computer and use it in GitHub Desktop.
Save AmirHosein-Gharaati/f0cbad2add3d9b491f4661e13c1db47d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Point {
char index;
int x, y;
};
int compare_struct(const void *a, const void *b){
struct Point *aa = (struct Point*)a;
struct Point *bb = (struct Point*)b;
// compare x*y
long long res_a = ((long long)aa->x * aa->y);
long long res_b = ((long long)bb->x * bb->y);
if(res_a > res_b)
return 1;
else if (res_a == res_b)
return 0;
else
return -1;
}
int main(){
struct Point arr[10];
const int count = 10;
srand(time(0));
for(int i = 0 ; i < count; i++)
arr[i] = (struct Point){.x = rand()%200, .y= rand()%200, .index=i};
// before sort
for(int i = 0; i < count ;i++){
printf("Point #%d\n\tindex: %d, x: %d, y: %d\n", i, arr[i].index, arr[i].x, arr[i].y);
}
printf("----\n");
qsort(arr, count, sizeof(struct Point), compare_struct);
// after sort
for(int i = 0; i < count ;i++){
printf("Point #%d\n\tindex: %d, x: %d, y: %d\n", i, arr[i].index, arr[i].x, arr[i].y);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment