You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pascal语言冒泡排序输出异常:仅显示0和1,请求错误排查

Pascal冒泡排序输出仅为0和1的问题修复

你的数组索引从0开始的写法没有问题,问题出在交换元素的逻辑上。

看这段错误的交换代码:

arr[j] := temp;
arr[j] := arr[j + 1];
arr[j + 1] := temp;

你提前把arr[j]赋值为初始值是0的temp,导致原有的arr[j]值直接丢失,最后arr[j+1]被设为0,这就是输出大量0的原因。

正确的交换逻辑应该是先把arr[j]的值暂存到temp里,再完成交换:

temp := arr[j];
arr[j] := arr[j + 1];
arr[j + 1] := temp;

修正后的完整代码:

program BubbleSort;

const n = 9;
var
    arr : array [0..n] of integer;
    a, b, i, j, temp : integer;
begin
    for a := 0 to n do
    begin
        writeln('Please enter the ', a, '-th element in the array:');
        readln(arr[a]);
    end;
    for i := 0 to (n - 1) do
    begin
        for j := 0 to (n - i - 1) do
        begin
            if (arr[j] > arr[j + 1]) then
            begin
                temp := arr[j];
                arr[j] := arr[j + 1];
                arr[j + 1] := temp;
            end;
        end;
    end;
    writeln('The sorted array is as follows:');
    for b := 0 to n do
    begin
        write(arr[b], ' ');
    end;
end.

另外,你声明的num变量没有被使用,可以直接删掉,避免冗余。

内容的提问来源于stack exchange,提问作者Tsain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:22:51