xiaoy的个人博客分享 http://blog.sciencenet.cn/u/xiaoy

博文

[用MATLAB写算法]之排序算法1)插入排序

已有 6232 次阅读 2017-3-13 13:09 |个人分类:算法学习|系统分类:科研笔记

简单的插入排序,算法复杂度为Θ(n2).


filename: insertion_sort

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function sorted_array=insertion_sort(num_array)
% sorted_array=insertion_sort(num_array)  ascending
% algorithm complexity: theta(n^2)

for i=2:length(num_array)
   for j=1:i-1
       if num_array(i)<num_array(j)
           tmp=num_array(i);
           for k=i-1:-1:j
               num_array(k+1)=num_array(k);
           end
           num_array(j)=tmp;
           break
       end
   end
end

sorted_array=num_array;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


运行示例:


insertion_sort.m.zip




https://blog.sciencenet.cn/blog-71294-1039179.html

上一篇:高校青年教师职业生涯初期中的困境
下一篇:[用MATLAB写算法]之排序算法2)归并排序merge sort
收藏 IP: 116.7.234.*| 热度|

1 张海权

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-24 19:26

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部