While playing around with as’ vector.sort() I found out that it behaves normally in every case except where it needs to sort a vector with only 2 or 3 distinctive values. If this is the case, the sort() function runs extremely slowly.
Here’s my code:
var test:Vector.<int>=new Vector.<int> ;
for (var i:int=0; i<6000; i++) {
test.push(Math.floor(Math.random()*2));
}
var timer:Number
var timer2:Number
timer=new Date().getTime();
test.sort(compare)
timer2=new Date().getTime();
trace(timer2-timer)
function compare(x:int,y:int):Number {
if (x>y) {
return 1;
} else if (x<y) {
return -1;
} else {
return 0;
}
}
simply copypaste this code.
What might be the problem here?
thanks.
This doesn’t actually happen with 2 or 3 values, more precisely, the effect is more noticeable the fewer distinct values there are in the vector. Each sorting algorithm has it’s cons and pros. The built-in one (I reckon it’s the bubble sort) will perform nearly it’s worst case when there are few distinct values. You could try this simple alternative (sort of radix sort), but notice that it will have larger memory footprint, and the larger the more distinct values there are in the vector.