Skip to content

Latest commit

 

History

History
61 lines (45 loc) · 2.75 KB

File metadata and controls

61 lines (45 loc) · 2.75 KB

Selection Sort

The selection sort is a simple sorting algorithm. As its name indicates, it selects the lowest element from the list and moves it where it should be.

Selection sort algorithm
  1. Start with the element in position 0.

  2. Find the minimum item in the rest of the array. If a new minimum is found, swap them.

  3. Repeat step #1 and #2 with the next element until the last one.

selection sort
Selection sort implementation

For implementing the selection sort, we need two indexes.

Selection sort
link:../../../src/algorithms/sorting/selection-sort.js[role=include]
  1. Converts any collection to an array or clone existing array.

  2. Visit all elements in the array starting from the 1st element (index 0).

  3. Everything to the left side is considered sorted in its final position. So, select left as the initial minimum value.

  4. Compare the selection to every element to the right side.

  5. If it finds a value smaller than the selection, then update the selection.

  6. Put the next smallest item to its final position

Tip
Selection sort minimizes the number of swaps. It does one swap per iteration while insertion sort and bubble sort could swap many times with the same array.

One index is for the position in question (selection/left) and another for finding the minimum in the rest of the array (right).

Selection Sort Properties

Why selection sort is not stable?

To recap, stable means that items with the same value keep their initial position. Let’s see what would happen with the selection sort if we (select) sort the following array 2, 5, 2, 1. To distinguish them, let’s say 2a and 2b, so 2a, 5, 2b, 1.

Initially, we select the first element, 2a and check if there’s anything less than 2 in the array. We find out that position 3 has an item with a smaller value (1), so we swap them.

Now, we have: 1, 5, 2b, 2a. There you have it, 2b now comes before 2a.