Learner Level

Implement the insertionSortArray method that returns the array after sorting it using insertion sort logic.

The input contains an integer array nums and its length size. Your task is to sort the array in ascending order using the insertion sort approach.

Insertion sort builds the sorted array from left to right. For example, [6,2,4,1] should become [1,2,4,6].

Example 1

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

Example 2

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

Example 3

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

Insertion sort keeps the left part of the array sorted.

Start from the second element. Treat the current value as the key and move all greater values in the sorted left part one position to the right. Then place the key in the empty position.

After processing every element, the whole array becomes sorted.

Pseudocode:

function insertionSortArray(nums, size):
    for i from 1 to size - 1:
        key = nums[i]
        j = i - 1
        while j >= 0 and nums[j] > key:
            nums[j + 1] = nums[j]
            j--
        nums[j + 1] = key
    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.