插入排序matalab
时间: 2023-09-26 09:08:21 浏览: 39
function sorted_arr = insertion_sort(arr)
% INSERTION_SORT sorts the input array using insertion sort algorithm
% sorted_arr = INSERTION_SORT(arr)
% arr - input array to be sorted
% sorted_arr - output sorted array
% get the length of the input array
n = length(arr);
% loop through each element in the array
for i = 2:n
% set the current element and the index of the previous element
current = arr(i);
j = i-1;
% loop through the previous elements until a smaller element is found
while j >= 1 && arr(j) > current
% move the previous element to the right
arr(j+1) = arr(j);
j = j-1;
end
% insert the current element in the correct position
arr(j+1) = current;
end
% return the sorted array
sorted_arr = arr;
end