DSA Lesson 23 of 33

Selection Sort

Learn how Selection Sort repeatedly selects the smallest element.

Course Progress70%

Theory

Selection Sort divides the array into sorted and unsorted parts. It repeatedly finds the smallest element in the unsorted part and places it at the beginning of that part. Its time complexity is O(n²).

Example

const numbers = [64, 25, 12, 22, 11]; for (let i = 0; i < numbers.length - 1; i++) { let minIndex = i; for (let j = i + 1; j < numbers.length; j++) { if (numbers[j] < numbers[minIndex]) { minIndex = j; } } const temp = numbers[i]; numbers[i] = numbers[minIndex]; numbers[minIndex] = temp; } console.log(numbers);

Expected Output

[11, 12, 22, 25, 64]

Practice

Implement Selection Sort for an array of integers.

Interview Questions

  1. How does Selection Sort work?
  2. What is its time complexity?
  3. How many major selections are made?
  4. How is Selection Sort different from Bubble Sort?