现在的位置: 首页 > 综合 > 正文

pl/sql 求二分法

2013年10月29日 ⁄ 综合 ⁄ 共 1211字 ⁄ 字号 评论关闭

create or replace procedure pr_half_find(in_num in number,in_arr in varchar2)
is

type arr_num is table of number index by binary_integer;
my_arr_num arr_num;
n_arr_index number(10):=0;

n_upper_bound number(10);
n_lower_bound number(10);
n_cur_index number(10);
begin

   for i in (select my_date from (
                    select regexp_substr(in_arr,'[^,]+',1,rownum) my_date from dual
                    connect by rownum<= length(in_arr) - length(replace(in_arr,',',''))+1
                    )
             order by to_number(my_date))
   loop
      n_arr_index := n_arr_index+1;
      my_arr_num(n_arr_index) := i.my_date;
      dbms_output.put_line(n_arr_index||'   '||my_arr_num(n_arr_index));

   end loop;
  
   n_upper_bound := 1;
   n_lower_bound := n_arr_index;
  
   if in_arr  is not null then
       while true
       loop
          n_cur_index := floor((n_upper_bound + n_lower_bound)/2);
          if my_arr_num(n_cur_index) = in_num then
             dbms_output.put_line('在第'||n_cur_index||'位');
             exit;
          end if;
         
          if n_upper_bound>=n_lower_bound then
             exit;
          end if;
          if my_arr_num(n_cur_index) > in_num then
             n_lower_bound := n_cur_index;
          else
             n_upper_bound := n_cur_index+1;
          end if;
         
       end loop;  
   end if;

end;

抱歉!评论已关闭.