我目前正在学习COBOL,我正在尝试在程序中实现冒泡排序算法。尽管我还是该语言的新手,但是我写的内容在语义和语法上对我来说都是有意义的,但是如果我按该顺序输入5、4、3、2和1,我的帖子排序表就会变成1、5 4,3,2。有人可以向我解释我哪里出错了吗?
IDENTIFICATION DIVISION.
PROGRAM-ID. BubbleSort.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 TVAR PIC 9(4).
01 CNT PIC 9(1) VALUE 1.
01 CNT2 PIC 9(1) VALUE 1.
01 ARR.
05 ARRELEMENT PIC 9(4) OCCURS 5 TIMES.
01 TABLELENGTH PIC 9(1) VALUE 5.
PROCEDURE DIVISION.
DISPLAY "Enter 5 numbers: ".
PERFORM INPUT-PARA VARYING CNT FROM 1 BY 1 UNTIL CNT>5.
DISPLAY "Pre Bubble-Sort: ".
PERFORM PRINT-PARA VARYING CNT FROM 1 BY 1 UNTIL CNT>5.
PERFORM BBLSORT-PARA.
DISPLAY "Post Bubble-Sort: ".
PERFORM PRINT-PARA VARYING CNT FROM 1 BY 1 UNTIL CNT>5.
STOP RUN.
INPUT-PARA.
ACCEPT ARRELEMENT(CNT).
PRINT-PARA.
DISPLAY "Table element: "ARRELEMENT(CNT).
BBLSORT-PARA.
INITIALIZE CNT CNT2.
MOVE 1 TO CNT.
MOVE 2 TO CNT2.
PERFORM UNTIL CNT>6
PERFORM UNTIL CNT2>5
DISPLAY "IF "ARRELEMENT(CNT) " IS > "ARRELEMENT(CNT2)
IF (ARRELEMENT((CNT)) > ARRELEMENT((CNT2)))
THEN
DISPLAY ARRELEMENT(CNT) " IS > "ARRELEMENT(CNT2)
MOVE ARRELEMENT(CNT) TO TVAR
MOVE ARRELEMENT(CNT2) TO ARRELEMENT(CNT)
MOVE TVAR TO ARRELEMENT(CNT2)
END-IF
DISPLAY "EXIT IF LOOP"
ADD 1 TO CNT2 GIVING CNT2
END-PERFORM
ADD 1 TO CNT GIVING CNT
END-PERFORM.
END PROGRAM BubbleSort.
免责声明:我不是COBOL程序员,但是通过对循环的这些更改,我能够完成这项工作。
PERFORM UNTIL CNT>4
MOVE 1 TO CNT2
PERFORM UNTIL CNT2+CNT>5
ADD 1 TO CNT2 GIVING CNT3
IF (ARRELEMENT((CNT2)) > ARRELEMENT((CNT3)))
THEN
DISPLAY ARRELEMENT(CNT2) " IS > "ARRELEMENT(CNT3)
MOVE ARRELEMENT(CNT3) TO TVAR
MOVE ARRELEMENT(CNT2) TO ARRELEMENT(CNT3)
MOVE TVAR TO ARRELEMENT(CNT2)
END-IF
DISPLAY "EXIT IF LOOP"
ADD 1 TO CNT2 GIVING CNT2
END-PERFORM
ADD 1 TO CNT GIVING CNT
END-PERFORM.
关键是添加一个我用来代表CNT2 + 1的CNT3。在内循环之前,有必要每次将CNT2重新发送为1。然后该算法将每次在循环中将项CNT2与项CNT2 + 1进行比较,而无需引用CNT。
而且,也不需要每次都一直循环到内部循环中的数组末尾。我发现参考Geeks for Geeks on bubble sort
有帮助