Recently I have been trying to create a bubble sort algorithm in Pascal language, however after the program is run, the output turned out to be only 0s and 1s. I wonder what have I done wrong.
program BubbleSort;
const n = 9;
var
arr : array [0..n] of integer;
num, a, b, i, j, temp : integer;
begin
temp := 0;
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
arr[j] := temp;
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.
Since I am familiar with C# and Java, I tried my best to declare the array to start from index 0, and that might be the cause of the problem. I have no idea.
You should write
temp := arr[j];
instead of
arr[j] := temp;