#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_SIZE 100
我试图快速排序基于从原点的距离2D点的数组,但我的代码打第一scanf
后Seg fault
。分段错误,但我不知道为什么
typedef struct point{
double x;
double y;
double dist;
} point;
void sortpoints(point arr[], int low, int high);
void printpoints(point arr[], int n);
Sortpoints只是在取决于Point.dist
void sortpoints(point arr[], int low, int high){
int piv, i, j;
piv = low;
i = low;
j = high;
point box;
if(low < high){
while(i<j){
while((arr[i].dist)<=(arr[piv].dist) && i<= high)
i++;
}
while((arr[j].dist) > (arr[piv].dist) && j>= low)
j--;
}
if(i<j){
box = arr[i];
arr[i] = arr[j];
arr[j] = box;
}
box = arr[j];
arr[j] = arr[piv];
arr[piv] = box;
sortpoints(arr, low, j-1);
sortpoints(arr, j+1, high);
}
Printpoints值排序的Point structs
阵列的快速排序的操作只是打印点在它们的距离的次序从原点
void printpoints(point arr[], int n){
int i; for(i = 0; i <= n; i++){
printf("(%.2lf, %.2lf)\n", arr[i].x, arr[i].y);
}
}
用户输入表格中点的数量和点的数量(point.x,point.y)
int main(){
point pointa;
point pointarray[MAX_SIZE];
int n=0;
printf("how many points would you like to enter?\n");
scanf("%d", &n);
if(n<MAX_SIZE){
int i;
for(i=0; i<n ; i++){
scanf("(%lf,%lf)", &pointa.x, &pointa.y);
pointa.dist = sqrt(pointa.x*pointa.x + pointa.y*pointa.y);
pointarray[i] = pointa;
}
sortpoints(pointarray, 0, n-1);
printpoints(pointarray, n);}
else{
printf("sorry, not a valid array size\n");
}
return 0;
}
这是一段时间,因为我重申了C中的运算符优先级...你可以用'&(pointa.x)'来尝试吗? – SJuan76
嘿,谢谢你的回复!刚刚尝试过,不幸的是没有运气。 – user3088836
@ SJuan76元素选择运算符'.'比'&'的地址具有更高的优先级,并且首先运行。 – Atle