Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP Arrays - Remove duplicates ( Time complexity )
    primarykey
    data
    text
    <p>Okay this is not a question of "how to get all uniques" or "How to remove duplicates from my array in php". This is a question about the time complexity.</p> <p>I figured that the <code>array_unique</code> is somewhat O(n^2 - n) and here's my implementation:</p> <pre><code>function array_unique2($array) { $to_return = array(); $current_index = 0; for ( $i = 0 ; $i &lt; count($array); $i++ ) { $current_is_unique = true; for ( $a = $i+1; $a &lt; count($array); $a++ ) { if ( $array[$i] == $array[$a] ) { $current_is_unique = false; break; } } if ( $current_is_unique ) { $to_return[$current_index] = $array[$i]; } } return $to_return; } </code></pre> <p>However when benchmarking this against the <code>array_unique</code> i got the following result:</p> <p>Testing (array_unique2)... Operation took 0.52146291732788 s. </p> <p>Testing (array_unique)... Operation took 0.28323101997375 s.</p> <p>Which makes the array_unique twice as fast, my question is, why ( Both had the same random data ) ?</p> <p>And a friend of mine wrote the following:</p> <pre><code>function array_unique2($a) { $n = array(); foreach ($a as $k=&gt;$v) if (!in_array($v,$n)) $n[$k]=$v; return $n; } </code></pre> <p>which is twice as fast as the built in one in php.</p> <p>I'd like to know, why?</p> <p>What is the time-complexity of array_unique and in_array?</p> <p><strong>Edit</strong> I removed the count($array) from both loops and just used a variable in the top of the function, that gained 2 seconds on 100 000 elements!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload