...

View Full Version : Resolved Array Sorting when using array of a class. (New question)



thooom
01-06-2012, 03:28 PM
I am currently making an array that is supposed to contain a bunch of classes with different statistics, and I want to be able to sort my tables after any of these numbers.

Array is built like this $array[count($array)] = new Class ($name, $int1, $int2, $int3, $int4, $int5);

Now comes the tricky part. I am trying to find out how to sort these something like sort($array[$i]->getInt1()); and I can't seem to wrap my head around how to get this done. Is this one of those things I need to create my own sorting algorithm to fix?

Sorry if this was confusing, but I am a bit confused myself, can't really point myself in the right direction either :confused:

Fou-Lu
01-06-2012, 03:38 PM
PHP has no built in graceful way of doing this since there is no equals, comparator or comparable interfacing. Forcing an override of __toString should actually work as the language typically defaults to strings as a last resort. This said, IMO __toString should not be used in this fashion.
Write a comparator for it instead, and use a usort.


function cmpMyClass(MyClass $c1, MyClass $c2)
{
return $c1->getInt1() - $c2->getInt1();
}

usort($array, 'cmpMyClass');

thooom
01-06-2012, 04:12 PM
Thanks for that, will look into it and hopefully figure it out. That was brand new for me!

thooom
01-06-2012, 04:55 PM
Tried this instead, but it seems to go into an infinite loops, anyone see why? It's a pretty standard Selection Sort.


function sortInt1($array)
{
for ($i = 0; $i < count($array); $i++)
{
$min = $i;
for ($j = $i+1; $j < count($array); $j++)
{
if ($array[$j]->getInt1() < $array[$i]->getInt1())
{
$min = $j;
}
}
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}

Fou-Lu
01-06-2012, 05:16 PM
This algorithm is wrong. Since $j always reaches that of sizeof($array) + 1, you effectively append endlessly onto the array. The infinite occurs since you always pull the count($array) in the loop condition (which is another good reason to not do so). It also won't change since you don't return anything nor is it referenced.
This will work:


function sortInt1(&$array)
{
$arSize = count($array);
for ($i = 0; $i < $arSize; $i++)
{
$min = $i;
for ($j = $i+1; $j < $arSize; $j++)
{
if ($array[$j]->getInt1() < $array[$min]->getInt1())
{
$min = $j;
}
}
if ($min != $i)
{
$temp = $array[$i];
$array[$i] = $array[$min];
$array[$min] = $temp;
}
}
}


I strongly recommend against using this. PHP's sort algorithm uses a quicksort, which overall will beat the selection sort. Selection is constant O(n^2), while quicksort is O(n^2) in worst case scenario (effectively a selection sort), while it averages O(nlogn). Use the builtin sort with a comparator instead.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum