Selection Sort Algorithm in Javascript

Mohsin KhansabMohsin Khansab
1 min read

Overview

  • O(n²) Time Complexity in all cases.

  • Does less “Memory writes” when compared with other algorithms such as Quick sort, Merge sort, Insertion sort and Bubble sort.

  • However, not an optimal algorithm in terms of “Memory writes”. There is other algorithm called Cycle sort which is optimal in terms of memory writes.

  • Basic idea for Heap sort.

  • Not Stable (order of elements may change).

  • In-Place Algorithm

Idea

  • Iterate through loop

  • First iteration, find the minimum element and put it in the first place.

  • Second iteration, find the minimum element and put it in the second place.

  • Repeat this process, at the end the array is sorted.

Code

Time Complexity

The internal for-loop runs:

$$\begin{align*} (n-1) + (n-2) + \dots + 2 + 1 \\ = \frac{n(n-1)}{2} \\ \theta(n^2) \end{align*}$$

0
Subscribe to my newsletter

Read articles from Mohsin Khansab directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohsin Khansab
Mohsin Khansab

Software engineer skilled in building web applications and REST APIs using Java, ReactJS, and Spring Boot. Experienced in agile teams, performance optimization, and code quality. Passionate about engineering and building scalable systems.