0

我需要帮助创建一个存储过程,该过程允许用户输入随机数列表,然后使用冒泡排序算法对它们进行排序。我对编程和 PL/SQL 都很陌生。任何帮助将非常感激。

以下是我到目前为止的代码行:

CREATE OR REPLACE PROCEDURE test_BubbleSort (i_number IN number) AS

type l_array_type IS TABLE OF NUMBER(10);

l_temp  NUMBER;

l_array l_array_type := l_array_type();

BEGIN

  --Loop through numbers and re-arrange their order using bubble sort---

  FOR i in 1 .. l_array.Count - 1 LOOP

    FOR j IN 2 .. l_array.Count LOOP
      IF l_array(j) > l_array(j - 1) THEN
        l_temp := l_array(j - 1);
        l_array(j - 1) := l_array(j);
        l_array(j) := l_temp;
      END IF;
    END LOOP;
  END LOOP;

  --Print the newly sorted numbers user inputs 

  FOR i in REVERSE 1 .. l_array.COUNT LOOP

    dbms_output.put_line('The new sorted numbers are: ' || l_array(i));
  END LOOP;

END;
4

2 回答 2

1

我不认为这真的是您想要的,但是如果您确实想自己生成随机数并且只希望用户提供列表的长度(as i_number),那么您可以循环执行此操作:

...
BEGIN

  --Generate some random numbers
  for i in 1..i_number loop
    l_array.extend;
    l_array(i) := dbms_random.value(1, 100);
  end loop;

  --Loop through numbers and re-arrange their order using bubble sort---

  FOR i in 1 .. l_array.Count - 1 LOOP
  ...

当使用i_number参数值 5 调用时,可能会给出:

The new sorted numbers are: 10
The new sorted numbers are: 55
The new sorted numbers are: 60
The new sorted numbers are: 74
The new sorted numbers are: 87

调用的参数dbms_random.value()限制了生成的“随机”数字的范围。

于 2013-04-29T15:49:54.693 回答
0

这是我最终得到的答案。只是想和大家分享!

CREATE OR REPLACE PROCEDURE test_BubbleSort1(i_number IN VARCHAR2)
IS
  --Local variables
  l_temp NUMBER;
  type l_array_type IS TABLE OF NUMBER(10);
  l_array l_array_type;
BEGIN
  --Parse values and dump into collections
  SELECT TRIM(SUBSTR(txt,
                 INSTR(txt, ',', 1, level) + 1,
                 INSTR(txt, ',', 1, level + 1) -
                 INSTR(txt, ',', 1, level) - 1)) BULK COLLECT
  INTO l_array
  FROM (select ',' || i_number || ',' AS txt FROM DUAL)
  CONNECT BY LEVEL <= LENGTH(i_number) - LENGTH(replace(i_number, ',', '')) + 1;

  --Loop through numbers and re-arrange their order using bubble sort
  FOR i in 1 .. l_array.LAST - 1
  LOOP
    FOR j IN 2 .. l_array.LAST
    LOOP
      IF l_array(j) > l_array(j - 1) THEN
        l_temp := l_array(j - 1);
        l_array(j - 1) := l_array(j);
        l_array(j) := l_temp;
      END IF;
    END LOOP;
  END LOOP;
  --Print the newly sorted numbers
  FOR k IN reverse 1 .. l_array.LAST
  LOOP
    DBMS_OUTPUT.PUT_LINE('The new sorted numbers are: ' || l_array(k));
  END Loop;
END;
于 2013-05-03T19:21:57.243 回答