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) =
4Returns (int[])
[1,2,4,6]Example 2
Input
nums (int[]) =
[3,1,2]size (int) =
3Returns (int[])
[1,2,3]Example 3
Input
nums (int[]) =
[8]size (int) =
1Returns (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 numsReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run