Back to Dashboard

Selection Sort

Easy

Problem Statement

Sort the elements with Selection Sort Algorithm

Examples

Example 1:

  • Input: nums = [5,2,3,1]
  • Output: [1,2,3,5]
  • Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).

Solution

class Solution {
    public int[] sortArray(int[] nums) {
        for (int i = 0; i < nums.length; i ++) {
            var minId = i;
            for (int j = i; j < nums.length; j ++) {
                if (nums[j] < nums[minId]) {
                    minId = j;
                }
            }
            
            int tmp = nums[minId];
            nums[minId] = nums[i];
            nums[i] = tmp;
        }
        return nums;
    }
}

Complexity Analysis

  • Time Complexity: $O(n^2)
  • Space Complexity: $O(n^2)

Status

Solved

Complexity

Time
O(n^2)
Space
O(1)

Tags

ArraySorting
View Problem Source