matlab用m文件实现插入排序算法
时间: 2023-04-29 11:00:35 浏览: 329
插入排序算法是一种简单的排序算法,其基本思想是将待排序的元素插入到已排序的序列中,从而得到一个新的有序序列。下面是用MATLAB编写插入排序算法的示例代码:
function sorted_array = insertion_sort(unsorted_array)
% 插入排序算法
% 输入:待排序的数组 unsorted_array
% 输出:排序后的数组 sorted_array
n = length(unsorted_array); % 获取数组长度
for i = 2:n % 从第二个元素开始遍历
key = unsorted_array(i); % 获取当前元素
j = i - 1; % 获取前一个元素的下标
while j > 0 && unsorted_array(j) > key % 如果前一个元素比当前元素大
unsorted_array(j+1) = unsorted_array(j); % 将前一个元素后移
j = j - 1; % 继续向前比较
end
unsorted_array(j+1) = key; % 将当前元素插入到正确的位置
end
sorted_array = unsorted_array; % 返回排序后的数组
end
调用该函数的示例代码如下:
unsorted_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; % 待排序的数组
sorted_array = insertion_sort(unsorted_array); % 调用插入排序算法
disp(sorted_array); % 输出排序后的数组
阅读全文
相关推荐


















