http://www.biotrainee.com/thread-1321-1-1.html
$my_pos=$ARGV[0];
subnearest_search{
my($array,$value,$low_index,$high_index)=@_;
$high_index=@{$array}-1 unless$high_index;
$low_index=0 unless$low_index;
## first check whether the arrary is sorted or not !
if($array->[$low_index] > $array->[$high_index]){
print"not sort array !!!\n";
last;
}
## then check
if($value< $array->[$low_index] ){
if($value< ($array->[$low_index] + $array->[$low_index-1] )/2){
return$low_index-1
}else{
return$low_index
}
}elsif($value> $array->[$high_index]){
if($value< ($array->[$high_index] + $array->[$high_index-1] )/2){
return$high_index
}else{
return$high_index+1
}
}
$mid_index=int(($low_index+$high_index)/2);
if($array->[$mid_index] == $value) {
return$mid_index;
}
elsif($array->[$mid_index] < $value) {
&nearest_search($array,$value,$mid_index+1,$high_index);
}
else{
&nearest_search($array,$value,$low_index,$mid_index-1);
}
}
openFH,"hg38.tss";
while(<FH>){
chomp;
@F=split;
$chr{$F[1]}->{$F[2]}=[($F[0],$F[4])]
}
closeFH;
foreach(keys%chr){
$sort_pos{$_}=[sort{$a<=>$b}keys%{$chr{$_}}];
}
#print join"\n",@{$sort_pos{'chr1'}}[0..10],'\n';
$nearest_index=&nearest_search($sort_pos{'chr1'},$my_pos);
$nearest_pos=${$sort_pos{'chr1'}}[$nearest_index];
$up_pos=${$sort_pos{'chr1'}}[$nearest_index-1];
$down_pos=${$sort_pos{'chr1'}}[$nearest_index+1];
print"$nearest_index\t$up_pos\t$nearest_pos\t$down_pos\n";