Skip to main content
Known Participant
September 2, 2014
Question

Vector/Array sorting with custom compare function bug

  • September 2, 2014
  • 0 replies
  • 347 views

Hi,

can someone help me to understand custom compare function behavior when sorting Vector or Array of custom objects? The problem I have is really strange and I made small test which I'll share now.

I have created Vector (and tried with Array also later, it's the same) with 5 simple objects. Objects have only 2 variables, "a" and "b". All Objects have the "a" value equal to 1 and "b" values are consecutive numbers from 1 up to 5. Custom compare function compares and sorts these objects on "a" variable and here I have strange behavior. With every call of sort function using this custom compare function 1st and middle object (in 5 element vector it's 3rd, in 10 element vector it's 6th and so on) replace them selves in Vector object.

I have put the code below:

var objects:Vector.<Object> = new <Object>[{a:1, b:1}, {a:1, b:2}, {a:1, b:3}, {a:1, b:4}, {a:1, b:5}];

function sortVector(a:Object, b:Object):int

{

  if(a.a < b.a)

       return -1;

  else if(a.a > b.a)

       return 1;

  return 0;

}

var i:uint;

for(i=0; i<objects.length; i++)

  trace(objects.b);

//Output: 1, 2, 3, 4, 5

objects.sort(sortVector);

for(i=0; i<objects.length; i++)

  trace(objects.b);

//Output: 3, 2, 1, 4, 5

objects.sort(sortVector);


for(i=0; i<objects.length; i++)

  trace(objects.b);

//Output: 1, 2, 3, 4, 5

It's strange for me that sort function exchange two elements when they have equal compare values. Custom compare function above will actually always return 0 which means that elements have same compare values. And if this is regular behavior, why it doesn't exchange all other elements?

Does anyone have idea what's going on here?

This topic has been closed for replies.