RedEnginePress logo
RedEnginePress
AlgorithmsLanguagesPlaygroundAbout

Selection Sort

v
S
D
p
O
A
R
P
and 4 more contributors
/* The selection sort algorithm sorts an array by repeatedly finding the minimum element
 *(considering ascending order) from unsorted part and putting it at the beginning. The
 *algorithm maintains two subarrays in a given array.
 *1) The subarray which is already sorted.
 *2) Remaining subarray which is unsorted.
 *
 *In every iteration of selection sort, the minimum element (considering ascending order)
 *from the unsorted subarray is picked and moved to the sorted subarray.
 */

export const selectionSort = (list) => {
  if (!Array.isArray(list)) {
    throw new TypeError('Given input is not an array')
  }
  const items = [...list] // We don't want to modify the original array
  const length = items.length
  for (let i = 0; i < length - 1; i++) {
    if (typeof items[i] !== 'number') {
      throw new TypeError('One of the items in your array is not a number')
    }
    // Number of passes
    let min = i // min holds the current minimum number position for each pass; i holds the Initial min number
    for (let j = i + 1; j < length; j++) {
      // Note that j = i + 1 as we only need to go through unsorted array
      if (items[j] < items[min]) {
        // Compare the numbers
        min = j // Change the current min number position if a smaller num is found
      }
    }
    if (min !== i) {
      // After each pass, if the current min num != initial min num, exchange the position.
      // Swap the numbers
      ;[items[i], items[min]] = [items[min], items[i]]
    }
  }
  return items
}
About this Algorithm

Problem Statement

Given an unsorted array of n elements, write a function to sort the array

Approach

  • select the smallest element from the array
  • put it at the beginning of the array
  • then select the smallest array from the remaining unsorted list
  • append it to the sorted array at the beginning
  • keep doing this for every element of the array
  • repeat the above process n times

Time Complexity

O(n^2) Worst case performance

O(n^2) Best-case performance

O(n^2) Average performance

Space Complexity

O(1) Worst case

Example

arr[] = {80, 10, 40, 30}
Indexes: 0   1   2   3    

1. Index = 0
	Select the minimum number from the array (between index 0-3), ie, 10
2. Swap 10  and 80 (arr[0])
3. The array now is {10, 80, 40, 30}

4. Index = 1
	Select the minimum number from the array (between index 1-3), ie, 30
5. Swap 30 and 80 (arr[1])
6. The array now is {10, 30, 40, 80}

7. Index = 2
	Select the minimum number from the array (between index 2-3), ie, 40
8. Swap 40 and 40 (arr[2])
9. The array now is {10, 30, 40, 80}

The array is now sorted.

Video Explanation

A video explaining the Selection Sort Algorithm

Animation Explanation