Skip to main content

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?

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);
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
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.
Anonymous said…
##Deadeasy##

Popular posts from this blog

Attraction, Status, and the Curious Pattern Behind Some Marriages

There has been a lot of discussion lately about celebrity divorces. As someone who closely observes human behavior, I have been thinking about a possible pattern behind some relationships. Before explaining my thought, I should mention something about my own background. From childhood, I was never particularly drawn to the idea of physical beauty. In fact, I even had a somewhat negative view of it. This may have come from the value systems around me while growing up. I also remember a religious gathering where someone said that a woman's beauty reflects her inner mind. Even at that time, I instinctively rejected that idea. Over the years, however, I have started noticing certain patterns in couples. When couples walk closely together, sit near each other, and interact affectionately in public, there often seems to be an interesting dynamic. In many such cases, the woman appears more attractive than the man. Sometimes she also seems more powerful in...

Idea crazy and free advices on rise

Just for the sake of record, I have noted that "idea crazy" people who think theirs is novel and should be kept secret are on rise. Though I agree to some extent that the ideas be kept secret to get pioneership [sic] credit, I wonder, why they can't compare Coca cola and Pepsi. People giving "free advices" on "ideas" are also on rise.