1 | #include <stdlib.h> |
---|
2 | #include <stdio.h> |
---|
3 | #include <math.h> |
---|
4 | |
---|
5 | #define UNLIMIT |
---|
6 | #define MAXARRAY 60000 /* this number, if too large, will cause a seg. fault!! */ |
---|
7 | |
---|
8 | struct my3DVertexStruct { |
---|
9 | int x, y, z; |
---|
10 | double distance; |
---|
11 | }; |
---|
12 | |
---|
13 | int compare_my3DVertexStruct(const void *elem1, const void *elem2) |
---|
14 | { |
---|
15 | /* D = [(x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2]^(1/2) */ |
---|
16 | /* sort based on distances from the origin... */ |
---|
17 | |
---|
18 | double distance1, distance2; |
---|
19 | |
---|
20 | distance1 = (*((struct my3DVertexStruct *)elem1)).distance; |
---|
21 | distance2 = (*((struct my3DVertexStruct *)elem2)).distance; |
---|
22 | |
---|
23 | return (distance1 > distance2) ? 1 : ((distance1 == distance2) ? 0 : -1); |
---|
24 | } |
---|
25 | |
---|
26 | |
---|
27 | int |
---|
28 | main_qsort_large(int argc, char *argv[]) { |
---|
29 | struct my3DVertexStruct array[MAXARRAY]; |
---|
30 | FILE *fp; |
---|
31 | int i,count=0; |
---|
32 | int x, y, z; |
---|
33 | |
---|
34 | if (argc<2) { |
---|
35 | fprintf(stderr,"Usage: qsort_large <file>\n"); |
---|
36 | exit(-1); |
---|
37 | } |
---|
38 | else { |
---|
39 | fp = fopen(argv[1],"r"); |
---|
40 | |
---|
41 | while((fscanf(fp, "%d", &x) == 1) && (fscanf(fp, "%d", &y) == 1) && (fscanf(fp, "%d", &z) == 1) && (count < MAXARRAY)) { |
---|
42 | array[count].x = x; |
---|
43 | array[count].y = y; |
---|
44 | array[count].z = z; |
---|
45 | array[count].distance = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)); |
---|
46 | count++; |
---|
47 | } |
---|
48 | } |
---|
49 | printf("\nSorting %d vectors based on distance from the origin.\n\n",count); |
---|
50 | qsort(array,count,sizeof(struct my3DVertexStruct),compare_my3DVertexStruct); |
---|
51 | |
---|
52 | for(i=0;i<count;i++) |
---|
53 | printf("%d %d %d\n", array[i].x, array[i].y, array[i].z); |
---|
54 | return 0; |
---|
55 | } |
---|