Learner Level

Implement the selectionSortArray method that returns the array after sorting it using selection sort logic.

The input contains an integer array nums and its length size. Your task is to return the array sorted in ascending order using the selection sort idea.

Selection sort repeatedly selects the smallest value from the unsorted part of the array and places it at the current position. For example, [5,2,9,1] becomes [1,2,5,9].

Example 1

Input
nums (int[]) = [5,2,9,1]
size (int) = 4
Returns (int[]) [1,2,5,9]

Example 2

Input
nums (int[]) = [3,3,1]
size (int) = 3
Returns (int[]) [1,3,3]

Example 3

Input
nums (int[]) = [1]
size (int) = 1
Returns (int[]) [1]

Divide the array into two parts: sorted and unsorted.

For each position, find the smallest element in the remaining unsorted part and swap it with the current position. After each pass, one more element is fixed in its correct sorted position.

Pseudocode:

function selectionSortArray(nums, size):
    for i from 0 to size - 2:
        minIndex = i
        for j from i + 1 to size - 1:
            if nums[j] < nums[minIndex]:
                minIndex = j
        swap nums[i] and nums[minIndex]
    return nums
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.