日期:2014-05-17  浏览次数:20959 次

貌似有些难度,关于通过生成的数字进行排序的
现代码如下

declare 
a1 number;
temp varchar2(120);
sixnum varchar2(120);
begin
sixnum:=' ';
temp:=' ';
while (length(sixnum)<14) loop
  loop
  --生成号码
  a1:= floor( dbms_random.value(1,33));
  if a1<10 and a1>0 then
  temp:='0'||a1;
  dbms_output.put_line(temp);
  else 
  temp:=a1;
  dbms_output.put_line(temp);
  end if;
  if instr(sixnum,temp,1,1)<=0 then --找不到 
  sixnum:=sixnum||temp;
  exit;
  end if ; 
  end loop;
end loop;
  dbms_output.put_line(sixnum);
end;



接着我想把生成的数字从大到小进行排序,请问如何排序?

------解决方案--------------------
实测代码请参考:
SQL code

DECLARE
    a1 NUMBER;
    temp VARCHAR2(120);
    sixnum VARCHAR2(120);
    i INTEGER;
    j INTEGER;
    -- 定义数组类型
    TYPE ArrayType IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
    -- 定义数组
    arr ArrayType;
    -- 定义起泡排序标志变量
    flag INTEGER := 0;
    -- 起泡排序的交换变量
    t INTEGER;
    
BEGIN
    sixnum:=' ';
    temp:=' ';
    i := 0;
    WHILE (length(sixnum)<14) LOOP
        LOOP
            --生成号码
            a1:= floor( dbms_random.value(1,33));
            IF a1<10 AND a1>0 THEN
                temp:='0'||a1;
                dbms_output.put_line(temp);
            ELSE  
                temp:=a1;
                dbms_output.put_line(temp);
            END IF;
            IF instr(sixnum,temp,1,1)<=0 THEN --找不到  
                sixnum:=sixnum||temp;
                arr(i) := temp;
                i := i + 1;
                EXIT;
            END IF ;  
        END LOOP;
    END LOOP;
    dbms_output.put_line(sixnum);
    
    -- 进行起泡排序
    FOR i IN 0..arr.count - 1 LOOP
        flag := 1;
        FOR j IN 0..arr.count - i - 2 LOOP
            IF arr(j) < arr(j + 1) THEN
                flag := 0;
                t := arr(j);
                arr(j) := arr(j+1);
                arr(j+1) := t;
            END IF;
        END LOOP;
        IF flag = 1 THEN
            EXIT;
        END IF;
    END LOOP;   
    
    DBMS_OUTPUT.PUT_LINE('排序后的结果');
    FOR i IN 0..arr.count - 1 LOOP
        DBMS_OUTPUT.PUT_LINE(arr(i) || ', ');
    END LOOP; 
END;

------解决方案--------------------
SQL> create or replace type a1_arr IS VARRAY(7) of numbe
2 /

SQL> declare
2 --a1 number;
3 a1 a1_arr := a1_arr(0,0,0,0,0,0,0);
4 i number;
5 temp varchar2(120);
6 sixnum varchar2(120);
7 begin
8 sixnum:=' ';
9 temp:=' ';
 10 i :=1 ;
 11 while (length(sixnum)<21) loop
 12 loop
 13 --生成号码
 14 a1(i):= floor( dbms_random.value(1,33));
 15 if a1(i)<10 and a1(i)>0 then
 16 temp:='*0'||a1(i);
 17 dbms_output.put_line(temp);
 18 else
 19 temp:='*'||a1(i);
 20 dbms_output.put_line(temp);
 21 end if;
 22
 23 if instr(sixnum,temp,1,1)<=0 then --找不到
 24 sixnum:=sixnum||temp;
 25 exit;
 26 end if ;
 27 end loop;
 28 i:=i+1 ;
 29 end loop;
 30 dbms_output.put_line(sixnum);
 31 --数组排序
 32 for i IN 1.. 7 LOOP
 33 for j IN 1..6 LOOP
 34 if a1(i) < a1(j) then
 35 temp := a1(i);
 36 a1(i) := a1(j);
 37 a1(j) := temp ;
 38 end if;
 39 end loop;
 40 END LOOP;
 41 --输出