如果按记录中的编号对记录进行排序,但某些记录具有相同的编号,则顺序不能保证,但不应该是随机的?
假设我们按记录中的数字对某些记录进行排序:
Name Number_of_Language_Known
John 3
Mary 2
Peter 3
Mike 1
...
如果我们不按 Name
排序,则不能保证 John 和 Peter 的顺序,但如果记录从未改变?我认为在大多数环境下应该都是如此(即没有其他任何改变,并且排序进行了两次)。
也就是说,如果我们排序一次,就不会是彼得在约翰之前,而第二次则不会是约翰在彼得之前。
这是因为在 Ruby on Rails 环境中,如果从 DB 中获取记录,然后通过 Ruby 函数排序,并作为原始页面内容打印,顺序是一种方式,但如果之后通过 AJAX 请求数据,则对于该数字字段中具有相同数字的记录,排序后的数组元素可以具有不同的顺序,这看起来很奇怪。
更新:如果数据来自数据库,那么在获取记录时数据库可能会有不可预测的顺序。但是,如果记录首先按主 ID 排序怎么办?此外,如果数据已经位于数据结构内部,我不知道有任何常见的排序算法每次都会产生不同的排序顺序。也就是说,顺序不保证,但不随机。
Let's say if we are sorting some records by a number in record:
Name Number_of_Language_Known
John 3
Mary 2
Peter 3
Mike 1
...
If we are not also sorting by Name
, then the order of John and Peter is not guaranteed, but it shouldn't be random if the records never changed? I think it should be true in most environment (that is, nothing else changed, and the sorting is done twice).
That is, if we sort it one time, it won't be Peter before John and the second time, John before Peter.
This is because in a Ruby on Rails environment, if the records are fetched from DB and then sorted by a Ruby function, and printed as the original page content, the order is one way, but if the data is requested through AJAX afterwards, then the sorted array elements can have a different order, for records with the same number in that number field, and that seems strange.
Update: if the data is from the db, then maybe the db can have unpredictable order when records are fetched. But what if the records are sorted by primary ID in the first place? Also if the data is right inside the data structure already, I don't know any common sorting algorithm that will produce different sorting order each time. That is, order not guaranteed but not random.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“不保证”意味着它可以随时更改(取决于当前的内存布局、垃圾收集器、时间……)如果您需要另一个属性的排序顺序保持稳定,则必须按两个属性对其进行排序(按 ID,然后按名称 - 根据您的情况)
"not guaranteed" means it can change whenever it likes (depending on the current memory layout, the garbage collector, the time, ...) if you need the sort order of another attribute to be stable you have to sort it by both attributes (by id and then by name - in your case)
假设这些值来自 Active Record 模型,则排序来自数据库本身。不同的数据库以不同的方式处理排序,因此您可能需要检查特定数据库的文档。
Assuming these values are coming from an Active Record model, the ordering is coming from the database itself. Different databases handled ordering in different ways, so you will probably need to check the docs for your specific db.