Tag Archives: Negation

Beginning Algorithm Complexity and Estimation

Which is the Fastest Program?


When a programmer sees a chunk of code he tends to evaluate it in a rather intuitive manner and to qualify it as “elegant” or not. This is quite easy, because it’s subjective and nobody knows what exactly elegant means. However behind this there is a powerful mathematical approach of measuring a program effectiveness.

It’s a pity that most of the developers still think of the big O notation as something from the university classes, but unusual in the practice and they barely use it their job. But before describing the big O notation, let me start from something really simple.

Let’s have the following example (note that all the examples are in PHP):

$n = 100;
$s = 0;
 
for ($i = 0; $i < $n; $i++) {
	for ($j = 0; $j < $n; $j++) {
		$s++;	
	}	
}

As you can see there are two assignments and two nested loops. This is really a widely used example from any algorithm book.

Constants, Languages, Compilers

First of all the time to assign a value to a variable, to compare two values and to increment a variable is constant. It depends on the computer resources, the compiler or the language, but it’s constant on one machine if you compare two chunks of code. Now we can see that these operations take (add) constant time to the program, and we can assume this time is respectively a, b, c, d, e, f, g, h, i.

$n = 100; 	// a
$s = 0;		// b
$i = 0; 	// c
$i < $n; 	// d
$i++;		// e
$j = 0; 	// f
$j < $n;	// g
$j++;		// h
$s++;		// i

What Matters?

Actually the most important thing here is the value of n. By assigning greater values to n the more time will take the program to run. As we can see from the following table by multiplying the value of n by 10, the time became 100 times more.

n		time
10		0.00002
100		0.002
...		...

What happens in fact is that we can sum all these values.

a + b + c + n*d + n*e + n*(f + n*g + n*h + n*i)

and by substituting:

a + b + c = k
d + e + n = l
g + h + i = m

the result is:

m*+ l*n + k

Conclusion

Here the most important thing is the degree of n, because it can change dramatically the program time consumption depending on the n value. Thus this chunk has a quadratic complexity or O(n²).

Of course there are constants, but in the practice they are not so important. Take a look at these two functions:

f = 2*n²
g = 200*n

OK, for n = 1 the first one will be faster, but as n increments the second function becomes to be faster and faster, thus after a given value of n the second function is really the fastest!

Friday Algorithms: Quicksort – Difference Between PHP and JavaScript

Here’s some Friday fun. Let me show you one sorting algorithm, perhaps the most known of all them – the quick sort, implemented both on PHP and JavaScript. Although the code look similar between both languages, there are few differences, that show the importance of the syntax knowledge!

1. PHP

<?php
 
    $unsorted = array(2,4,5,63,4,5,63,2,4,43);
 
    function quicksort($array)
    {
        if (count($array) == 0)
            return array();
 
        $pivot = $array[0];
        $left = $right = array();
 
        for ($i = 1; $i < count($array); $i++) {
            if ($array[$i] < $pivot)
                $left[] = $array[$i];
            else
                $right[] = $array[$i];
        }
 
        return array_merge(quicksort($left), array($pivot), quicksort($right));
    }
 
    $sorted = quicksort($unsorted);
 
    print_r($sorted);

2. JavaScript

var a = [2,4,5,63,4,5,63,2,4,43];
 
function quicksort(arr)
{
    if (arr.length == 0)
        return [];
 
    var left = new Array();
    var right = new Array();
    var pivot = arr[0];
 
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] < pivot) {
           left.push(arr[i]);
        } else {
           right.push(arr[i]);
        }
    }
 
    return quicksort(left).concat(pivot, quicksort(right));
}
 
console.log(quicksort(a));

Note that the first conditional statement is quite important! While in PHP the count function will return 0 either on a NULL value or an empty array and you can substitute it with something like count($array) < 2

if (count($array) < 2)
	return $array;

in JavaScript you cannot use that because of the presence of the ‘undefined’ value when an “empty” array is passed as an argument. Thus you’ve the conditional above:

// this will result with an error
if (arr.length < 2)
        return arr;

Coming Up Next …

An iterative version of the algorithm next Friday!

JavaScript Objects Coding Style

JavaScript vs. PHP

Continuing from my post about PHP arrays coding style and following the comments of that post, I’d like to write a bit about JavaScript objects’ coding style.

You perhaps know that the term object is quite undefined or under estimated in the JavaScript world, but I’d speak about the key/value pairs in JS commonly formatted like that:

var obj = { key : 'value' }

Here you can add more and more key/value pairs, but what’s different from the PHP associative arrays and what’s the same and should be cosidered.

The Same as PHP?

I wrote about the alignment in PHP and hashes. Than I showed how I align them:

$arr = array(
   'short'   => 'val',
   'longkey' => 'val'
);

In JavaScript you should use the same technique of alignment:

var obj = {
   'short'   : 'val',
   'longkey' : 'val'
};

Some Differences

Yes, there are more differences, which is normal. First of all you don’t have the => notation in JavaScript and a : is used. Second and most important you cannot add a trailing comma after the last key/value pair. Note that in PHP that’s fine!

// that will throw an error in MSIE
var obj = {
   'short'   : 'val',
   'longkey' : 'val',
};

while this is OK in PHP and it’s encouraged:

$arr = array(
   'short'   => 'val',
   'longkey' => 'val',
);

Javascript Libraries Popularity

JavaScript and Market Share?!

It’s kind of strange to speak about JavaScript libraries and market share, so lets called it “popularity”. Have you ever been interested on which is the most famous JS library.

I’d guess everybody has the answer in his head, right? jQuery is becoming for the JS community something like Google for the web or IE6 on the browser’s market in the beginning of the century. How odd?!

However here’s a short list of who’s first.

1. Robert Nyman’s poll:

Note: original poll page’s here.

Clear enough jQuery rocks. As I personally use jQuery I still think that its success is based on his easy to start nature. However lets see another result chart.

2. Chris Coyier from http://css-tricks.com is showing almost the same result:

Note: original poll can be found here.

3. Finally Polldaddy’s hosting a poll, where the results are even more interesting.

Polldaddy

Note: original source of the poll.

From these results I get more surprised not so much from the jQuery big advantage, but more from YUI. It’s a really very very powerful JavaScript library, perhaps misunderstood maybe because of it’s native complexity, don’t know?!