Rating normalization algorithm I have a rating system where users can vote between 1-6. I'd like to normalize the votes a bit to better accommodate for extreme voting, where individuals tend to vote as high or as low as possible. To do this, I have the following algorithm which seems to work well. However, it's extremely inefficient and not very well written.

What might I do to improve it?

protected function calculateWeightedAverage($ratings)
{
    $values = array_values($ratings);
    sort($values);

    $count = count($values);
    $weights = array_fill(0, $count, 1);

    $out = (int) ($count / 3);
    $out2 = pow($out + 1, 2);

    $max = $count - 1;
    $min = 0;

    for ($i = 0; $i &lt; $out; $i++) {
        $j = $i + 1;
        $weights[$min + $i] = $j * $j / $out2;
        $weights[$max - $i] = $j * $j / $out2;
    }

    $sum = array_sum($weights);

    for ($i = 0; $i &lt; $count; $i++) {
        $weights[$i] /= $sum;
    }

    $rating = 0;
    for ($i = 0; $i &lt; $count; $i++) {
        $rating += $values[$i] * $weights[$i];
    }

    return $rating;
}
Your code is really good and I can't see any significant way to improve it. One minor improvement is to reduce the number of loops from 3 to 2:

protected function calculateWeightedAverage($ratings)
{
  $sum = 0;
  $rating = 0;

  $values = array_values($ratings);
  sort($values);

  $count = count($values);
  $out = (int) ($count / 3);
  $out2 = pow($out + 1, 2);

  for ($i=0; $i&lt;$count; $i++) {
    if ($i &lt; $out) {
      $weights[$i] = pow(($i+1),2)/$out2;
    } elseif ($i &gt; $count-$out-1) {
      $weights[$i] = pow($count-$i,2)/$out2;
    } else {
      $weights[$i] = 1;
    }
    $sum += $weights[$i];
  }

  for ($i = 0; $i &lt; $count; $i++) {
    $rating += $values[$i] * $weights[$i]/$sum;
  }

  return $rating;
}