C 结构排序
我想用C语言对这个问题进行排序,比如冒泡排序。。。任何人都可以帮忙 实现一个列表,其中5个结构点为a点w/X,y; 对5个结构点进行排序,首先计算x,然后计算y。 例如:C 结构排序,c,arrays,structure,bubble-sort,C,Arrays,Structure,Bubble Sort,我想用C语言对这个问题进行排序,比如冒泡排序。。。任何人都可以帮忙 实现一个列表,其中5个结构点为a点w/X,y; 对5个结构点进行排序,首先计算x,然后计算y。 例如: // The points p[0]={2,3} p[1]={4,5} p[2]={1,5} p[3]={4,3} p[4]={1,2} // Should become p[0]={1,2} p[1]={1,5} p[2]={2,3} p[3]={4,3} p[4]={4
// The points
p[0]={2,3}
p[1]={4,5}
p[2]={1,5}
p[3]={4,3}
p[4]={1,2}
// Should become
p[0]={1,2}
p[1]={1,5}
p[2]={2,3}
p[3]={4,3}
p[4]={4,5}
OP要求的是C解决方案,因此您可以:
void bsortDesc(struct yourStruct list[80], int s)
{
int i, j;
struct yourStruct temp;
for (i = 0; i < s - 1; i++)
{
for (j = 0; j < (s - 1-i); j++)
{
if (list[j].marks < list[j + 1].marks)
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
另外,这里是我从中得到的:。如果你想对结构进行排序,你仍然需要将其分解为比较数字类型。考虑到这一点,让我们以您的观点为例:
struct tagPoint
{
int x;
int y;
};
typedef struct tagPoint Point;
现在,假设您有一个点数组,并且希望对其进行排序。您可以采取两种方法:
一,。对数组进行排序的简单函数:
void SortPointArray(Point* Points, unsigned int n)
{
/* This will sort the points with priority on the x and then the y value in ascending order. */
for(unsigned int i = 0; i < n-1; i++)
for(unsigned int j = i+1; j < n; j++)
{
if (Points[i].x > Points[j].x)
{
Point aux = Points[i];
Points[i] = Points[j];
Points[j] = aux;
}
else if ((Points[i].x == Points[j].x) && (Points[i].y > Points[j].y))
{
Point aux = Points[i];
Points[i] = Points[j];
Points[j] = aux;
}
}
}
只需使用以下函数对数组进行排序:
void SortPointArray(Point* Points, unsigned int n)
{
/* This will sort the points with priority on the x and then the y value in ascending order. */
for(unsigned int i = 0; i < n-1; i++)
for(unsigned int j = i+1; j < n; j++)
{
if (Points[i].x > Points[j].x)
{
Point aux = Points[i];
Points[i] = Points[j];
Points[j] = aux;
}
else if ((Points[i].x == Points[j].x) && (Points[i].y > Points[j].y))
{
Point aux = Points[i];
Points[i] = Points[j];
Points[j] = aux;
}
}
}
你如何使用它们
如果只想使用第一个SortPointArray函数,这就足够了:
int main()
{
Point Array[10];
/* Read the points. */
for(unsigned int i = 0; i < 10; i++)
scanf("%d %d", &Array[i].x, &Array[i].y);
SortPointArray(Array, 10);
/*Print the points.*/
for(unsigned int i = 0; i < 10; i++)
printf("%d %d\n", Array[i].x, Array[i].y);
return 0;
}
到目前为止,您编写了什么代码?您熟悉回调吗?你明白@zixuan给出的答案吗?我不是C语言的高手,但我想很快变成这样,这就是为什么我要练习这些问题。。。。到目前为止,我的代码位于下一个commentstruct点{intx,y;};int main{int n;scanf%d,n;结构点p[n];forint i=0;i
int main()
{
Point Array[10];
/* Read the points. */
for(unsigned int i = 0; i < 10; i++)
scanf("%d %d", &Array[i].x, &Array[i].y);
SortPointArray(Array, 10);
/*Print the points.*/
for(unsigned int i = 0; i < 10; i++)
printf("%d %d\n", Array[i].x, Array[i].y);
return 0;
}
int main()
{
Point Array[10];
/* Read the points. */
for(unsigned int i = 0; i < 10; i++)
scanf("%d %d", &Array[i].x, &Array[i].y);
Sort(Array, 10, sizeof(Point), ComparePoints, SwapPoints);
/*Print the points.*/
for(unsigned int i = 0; i < 10; i++)
printf("%d %d\n", Array[i].x, Array[i].y);
return 0;
}