StatCounter

Wednesday, December 01, 2004

Interview question #2

This is related to PHP's array.

An array has number of elements. All elements are integers and unique, which means there is no repetitive integers.
(e.g.) $foo = array(7, 5, 9, 13, 2, 8);

You have to sort the array, provided:
  1. You should scan the elements only once.
  2. You're not allowed to compare the elements when sorting. (i.e., you're not supposed to use any comparison operators)
  3. Sorted resultant array may not be the source array.
How will you do that?

7 comments:

Anonymous said...

$foo = array(7, 5, 9, 13, 2, 8);

reset($foo);

$bar = array();
$barcount = 0;
while ($foo <> array()) {
$bartemp = min($foo);
$bar[$barcount] = $bartemp;
unset($foo[array_search($bartemp, $foo)]);
$barcount++;
}
print_r($foo); //empty
echo "\n";
print_r($bar); //sorted!
?>


Result:
$foo is Array
(
)

$bar is Array
(
[0] => 2
[1] => 5
[2] => 7
[3] => 8
[4] => 9
[5] => 13
)

Anonymous said...

$bar = $foo;
sort($bar);
reset($bar);
print_r($bar);

R. Rajesh Jeba Anbiah said...

For comment#1:You are using min() which is again a comparison function. The answer is not that complex at all.

For comment#2:Are you kidding;)

Anonymous said...

http://us4.php.net/manual/en/language.operators.comparison.php

R. Rajesh Jeba Anbiah said...

For comment#4:I meant that you're not allowed to compare the elements in anyway (using operators or functions). Probably I should have worded it better.

jcm said...

Without any comparison, though it's quite dumb :-)
$foo = array(7, 5, 9, 13, 2, 8);
$newfoo = array();
$c = count($foo);
$i = 0;
while (count($newfoo) < $c) {
if (in_array($i, $foo)) $newfoo[] = $i;
$i++;
}
var_dump($newfoo);
?>

91 said...

##Deadeasy##