我如何执行插入排序但检查数组中元素的属性而不仅仅是元素?
抱歉,我确信这很简单,但我很累,无法弄清楚。
我有一个元素数组,每个元素实际上是一个粒子,它是一个数据结构(c 中的结构),其中包含粒子当前位置(int x,y,z)。 我想比较元素的 x 位置而不仅仅是元素本身。
查看维基百科上的伪代码,我尝试修改它以比较我想要的属性但我认为我做错了一些事情(可能很简单)。
这是我修改的内容:
for (i = 1; i<length; i++) {
value = particles[i].position.x;
j = i - 1;
while (j >= 0 && particles[j].position.x > value) {
particles[j+1] = particles[j];
j = j - 1;
}
particles[j+1] = particles[i];
}
如果有人能指出我的错误,那就太好了!
亚当
Sorry, I'm sure this is simple but I'm tired and can't figure it out.
I have an array of elements, each element is in fact a particle which is a data structure (a struct in c) containing, among other things the particles current position (int x,y,z). I want to compare the elements x position not just the element itself.
Looking at the pseudocode on wikipedia, I've attempted to modify it to compare the attribute I want but I think I've done something (probably simple) wrong.
Here's what I've modified:
for (i = 1; i<length; i++) {
value = particles[i].position.x;
j = i - 1;
while (j >= 0 && particles[j].position.x > value) {
particles[j+1] = particles[j];
j = j - 1;
}
particles[j+1] = particles[i];
}
If someone could point out my mistake that would be great!
Adam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二行用于存储第 i 个元素的临时副本,因为 while 循环会覆盖它。 然而,在最后第二行中,您正在读取被覆盖的值。 将您的代码更改为以下内容,它应该可以工作(已注释的更改):
Your 2nd line acts to store a temporary copy of the ith element, because the while loop overwrites it. Yet in your 2nd last line you're reading from the overwritten value. Change your code to the following and it should work (changes commented):
您需要交换粒子对象,而不是 x 坐标的值。 尝试:
You need to swap particle objects, not the values of the x coordinates. Try: