• Time complexity: O(n2)

Hi, in the second episode of the algorithms series I’d like to take a closer look at yet another simple sorting technique called selection sort. Similarly to bubble sort, it consists of two dependent loops, therefore it’s time complexity also equals to O(n2). It goes like this:

  1. While sorting the array in ascending order we set the first loop and the first element in the array as a minimum.
  2. We set up a second loop with a range of the second till the last element, as it doesn’t make much sense to compare the first element with itself.
  3. If any of the remaining elements in the array is lower than the first, we set it as a minimum.
  4. As a final step, the lowest value is swapped with the first value (at 0 index).
  5. The loop continues with j+1 element as a minimum and j+1+1 as the remaining range.

Here’s the presentation (credits to http://www.xybernetics.com):

 

  • JavaScript implementation example:


[source_code]

  • PHP implementation example:

[source_code]

There are currently no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.