Write a function insert that takes an array of integers in ascending order, the number of integers currently in the array, the total size of the array, and an integer to insert into the array. The function should insert the given integer into the array such that the array remains in sorted order. If the array is already full, the array should remain unchanged. The function should return the new number of elements in the array.

Respuesta :

Answer:

The code is written in MATLAB

function insert(array,integer,capacity,newInt)

if integer == capacity %if the array is full, the function returns the original array

result = array;

else

if newInt < array(1) %If the new integer is less than the first element, it copies the new integer as the new first element

array = [newInt array];

elseif newInt > array(end) %If the integer is greater than the last element, it copies the new integer as the new last element

array = [array newInt];

else %If the new integer is inside the array, then it checks its new place

for i = 1:length(array)-1

if array(i+1) > newInt % once the place of the new integer is found, the rest of the array is saved in a dummy array

dummy = array(i+1:end);

array(i+1) = newInt;

array(i+2:end) = '';%the rest of the array is deleted

array = [array dummy]; %concatanate the dummy array with the newInteger inserted array

break

end

end

end

end

fprintf('The inserted integer is %g\n', newInt);

fprintf('The new array is \n',array);

disp(array)