मुख्य कंटेंट तक स्किप करें
Back to ChallengesImplement Selection SortEasy 15 min

Implement Selection Sort

Write a function that takes in an array of integers and returns a sorted version of that array using the Selection Sort algorithm.

Selection sort divides the input list into two parts: a sorted sublist of items which is built up from left to right, and a sublist of the remaining unsorted items. It proceeds by finding the smallest element in the unsorted sublist, exchanging it with the leftmost unsorted element, and moving the sublist boundaries one element to the right.

Examples

Input: arr = [8, 5, 2, 9, 5, 6, 3]
Output: [2, 3, 5, 5, 6, 8, 9]
The array is sorted in ascending order.

Constraints

  • 1 <= arr.length <= 1000
  • -10^4 <= arr[i] <= 10^4

Complexity Analysis

Time
O(N^2)
nested loops to find the minimum in the remaining array.
Space
O(1)
sorts in place.

Test Cases

#1 Standard unsorted array
Input: arr = [8,5,2,9,5,6,3]
Expected: [2,3,5,5,6,8,9]
#2 Reverse sorted array
Input: arr = [9,8,7,6,5]
Expected: [5,6,7,8,9]
JavaScript
Output
Click "Run Code" to see output here...