I have the following problem that I'm having trouble with, particularly in some of the parts where some of the code is given to me.
Problem Description: Given an array of integers, return an array containing the same integers sorted from the largest to the smallest using insertion sort. We'll use the convention of considering only part of the array that begins at a given index and ends at another. In this way, a recursive call can work through any part of the array. The initial call will pass in index 0 and the index to the last element.
insertionSort([2, 1, 3, -2, 8], 0, 4) → [8, 3, 2, 1, -2]
insertionSort([2, 6, -4], 0, 2) → [6, 2, -4]
insertionSort([2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22], 0, 10) → [22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
Code Given:
public int[] insertionSort(int[] nums, int begin, int end) {
}
void insert(int[] nums, int begin, int end, int element) {
int index=end;
while(index>=begin && nums[index]<element) {
index--;
}
for(int i=end; i>index; i--) {
nums[i+1] = nums[i];
}
nums[index+1] = element;
}
What I'm having trouble with is understanding what the "element" variable means in the "insert" method.
Here is the code I have written for it.
public int[] insertionSort(int[] nums, int begin, int end) {
if(begin >= end) return nums;
else if (begin < end){
int element = nums.length;
insert(nums, begin, end, element);
insertionSort(nums, begin, end);
}
return nums;
}
void insert(int[] nums, int begin, int end, int element) {
int index=end;
while(index>=begin && nums[index]<element) {
index--;
}
for(int i=end; i>index; i--) {
nums[i+1] = nums[i];
}
nums[index+1] = element;
}
This are the errors I get from my code:
