perl

推荐列表 站点导航

当前位置:首页 > 脚本编程 > perl >

Perl合并有序数组算法

来源:网络整理  作者:  发布时间:2020-12-26 17:05
题目2年前面baidu的时候问的,看起来很简单,写起来还是容易错。当年太菜,写的少。现在写出来不错也不容易。...
合并两个有序数组。
 
题目2年前面baidu的时候问的,看起来很简单,写起来还是容易错。当年太菜,写的少。现在写出来不错也不容易。
4最简单的当然是新建一个数组然后一个个往里面放。
这个二分法插入是不额外开辟空间的。感觉复杂度还可以更低,但是弄起来会麻烦。再想想
my @a = (1,3,5,7); my @b = (1,2,4,6,8); my $start = 0; my $end = @a -1 ; for my $t (@b){ print "Tracking $t \n"; my $cur; #binary search do{ $cur = int(($start+$end)/2); $end = $cur if($t<$a[$cur]); $start = $cur if($t>$a[$cur]); if($t == $a[$cur]){ $end = $cur +1; $start = $cur; } } while($end-$start >1); #assign the proper postion $cur = $end; #if the value is larger than the last element in current array, then append thelement to the last ; if($t>$a[$end]){ $cur = $end+1; } #move elements after current postion with distance 1 for(my $i = @a-1; $i >= $cur; $i--){ $a[$i+1] = $a[$i]; } $a[$cur] = $t; $start = $cur; $end = @a-1; print "-----------@a---------------\n"; }

相关热词:

本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!

本文地址: https://v30.fanwenzhu.com/jiaob/perl/9447.shtml

相关文章
Copyright © www.juheyunku.com      关于 | 合作 | 声明 | 联系 | 更新 | 地图 | Tags

Perl合并有序数组算法

2020-12-26 编辑:

合并两个有序数组。
 
题目2年前面baidu的时候问的,看起来很简单,写起来还是容易错。当年太菜,写的少。现在写出来不错也不容易。
4最简单的当然是新建一个数组然后一个个往里面放。
这个二分法插入是不额外开辟空间的。感觉复杂度还可以更低,但是弄起来会麻烦。再想想
my @a = (1,3,5,7); my @b = (1,2,4,6,8); my $start = 0; my $end = @a -1 ; for my $t (@b){ print "Tracking $t \n"; my $cur; #binary search do{ $cur = int(($start+$end)/2); $end = $cur if($t<$a[$cur]); $start = $cur if($t>$a[$cur]); if($t == $a[$cur]){ $end = $cur +1; $start = $cur; } } while($end-$start >1); #assign the proper postion $cur = $end; #if the value is larger than the last element in current array, then append thelement to the last ; if($t>$a[$end]){ $cur = $end+1; } #move elements after current postion with distance 1 for(my $i = @a-1; $i >= $cur; $i--){ $a[$i+1] = $a[$i]; } $a[$cur] = $t; $start = $cur; $end = @a-1; print "-----------@a---------------\n"; }

本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供学习参考!
本文地址为 https://v30.fanwenzhu.com/jiaob/perl/9447.shtml

相关文章

风云图片

推荐阅读

返回perl频道首页