Home javascript Stable Sort by JS

Stable Sort by JS

Author

Date

Category

This is not a completely minimal example. I copied one-in-one code from my code. Data structure:
this.cellslayer.children – array of graphically primitives, which is displayed on the screen. It needs to be sorted. Each element of this array contains .Object – link to the object of the game logic for this item.

Cause sorting after modifying any of the objects of gaming logic.

Actually Implementation:

this.cellslayer.children.Foreach (Function (Item, I, Arr) {
 Arr [i] .INDEX = I;
});
this.cellslayer.children.sort (FUNCTION (A, B) {
 var res = a.object.mass - b.object.mass;
 Return Res == 0? a.index & lt; = B.INDEX: RES;
});

The problem is that overlapping objects with the same OBJECT.MASS >regularly (after each sorting) jump over each other.


Answer 1, Authority 100%

So you have with the same MASS and A.INDEX less than b.index , the comparison function will return TRUE, which For the sort purposes will be given to 1, and, accordingly, in the sorted array b will be in front of A .

Replace & lt; = on & gt; = and get a steady sorting.
Better, since the function that returns various data types is not the best programming tone, A.INDEX & LT; = B.INDEX It would be worth it to be replaced by A.INDEX - B.INDEX .


Answer 2, Authority 100%

For a “stable” sorting, you need to return 0 if you want to return 0. If more than 1 if less -1.

i.e.

function (a, b) {
 var res = a.object.mass - b.object.mass;
 Return Res == 0? (A.INDEX & LT; = B.INDEX? (A.INDEX == B.INDEX)? 0: false): Res;
}

More, it is possible to return the deduction that it simplifies the task. Return Res == 0? A.INDEX-B.INDEX: res;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions