snippetMinor
Pascal Bubble Sort Implementation
Viewed 0 times
pascalbubbleimplementationsort
Problem
I would prefer a review of:
Here's the code:
- Efficiency
- Standards
- Different approaches
Here's the code:
program bubbleSort;
var
toSort: array[1..5] of integer = (3, 25, 2, 69, 1);
passChanges: boolean = true;
counter, index, temp: integer;
begin
while passChanges do
begin
index := 1;
passChanges := false;
for index := 1 to length(toSort) - 1 do
begin
if (toSort[index] > toSort[index +1]) then
Begin
temp := toSort[index + 1];
toSort[index + 1] := toSort[index];
toSort[index] := temp;
passChanges := true;
end;
end;
end;
for counter := 1 to length(toSort) do
writeln(toSort[counter]);
readln;
end.Solution
As long as we're bumping this older question:
You don't need to iterate over the entire array every time. You could set a variable and decrement it. E.g.
Then before the loop
While this won't change the asymptotic analysis (still quadratic worst case), it can cut the effective time. This works because Bubble Sort is guaranteed to move the largest element in a segment to the last position in each pass. Once that's done, that element will no longer move. So we don't need to check it again and can reduce the segment size.
Note: it's been at least thirty years since I programmed in Pascal. And I was not an expert on Pascal syntax then. Please don't take anything I wrote as suggesting the correct Pascal way to do things. This is purely an algorithmic review.
for index := 1 to length(toSort) - 1 doYou don't need to iterate over the entire array every time. You could set a variable and decrement it. E.g.
unsortedCount: integer = length(toSort);Then before the loop
Dec (unsortedCount);While this won't change the asymptotic analysis (still quadratic worst case), it can cut the effective time. This works because Bubble Sort is guaranteed to move the largest element in a segment to the last position in each pass. Once that's done, that element will no longer move. So we don't need to check it again and can reduce the segment size.
Note: it's been at least thirty years since I programmed in Pascal. And I was not an expert on Pascal syntax then. Please don't take anything I wrote as suggesting the correct Pascal way to do things. This is purely an algorithmic review.
Code Snippets
for index := 1 to length(toSort) - 1 dounsortedCount: integer = length(toSort);Dec (unsortedCount);Context
StackExchange Code Review Q#158315, answer score: 5
Revisions (0)
No revisions yet.