开发者

If sorting records by a number in the record, but some records have the same number, the order is not gauranteed but shouldn't be random?

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 orig开发者_JS百科inal 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.


"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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜