Skip to content

Commit 62015f9

Browse files
authored
Add Bubble Sort in Pascal (TheRenegadeCoder#4801)
1 parent 59cac77 commit 62015f9

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed

archive/p/pascal/bubble_sort.pas

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
program BubbleSort;
2+
3+
{$mode objfpc}{$H+}
4+
5+
uses
6+
Classes, Generics.Collections, SysUtils;
7+
8+
type
9+
TIntegerList = specialize TList<Integer>;
10+
11+
procedure ShowUsage;
12+
begin
13+
Writeln('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"');
14+
Halt(1);
15+
end;
16+
17+
function ParseIntegerList(const S: string): TIntegerList;
18+
var
19+
Tokens: TStringArray;
20+
Token: string;
21+
Value: Integer;
22+
begin
23+
if S.Trim.IsEmpty then
24+
ShowUsage;
25+
26+
Tokens := S.Split([',']);
27+
Result := TIntegerList.Create;
28+
29+
for Token in Tokens do
30+
begin
31+
if not TryStrToInt(Trim(Token), Value) then
32+
begin
33+
Result.Free;
34+
ShowUsage;
35+
end;
36+
Result.Add(Value);
37+
end;
38+
39+
if Result.Count < 2 then
40+
begin
41+
Result.Free;
42+
ShowUsage;
43+
end;
44+
end;
45+
46+
function IsSorted(const A: TIntegerList): Boolean;
47+
var
48+
i: Integer;
49+
begin
50+
for i := 1 to A.Count - 1 do
51+
if A[i] < A[i - 1] then
52+
Exit(False);
53+
Result := True;
54+
end;
55+
56+
procedure BubbleSort(List: TIntegerList);
57+
var
58+
i, j: Integer;
59+
Swapped: Boolean;
60+
61+
procedure SwapElements(Index1, Index2: Integer);
62+
var
63+
Temp: Integer;
64+
begin
65+
Temp := List[Index1];
66+
List[Index1] := List[Index2];
67+
List[Index2] := Temp;
68+
end;
69+
begin
70+
for i := List.Count - 1 downto 1 do
71+
begin
72+
Swapped := False;
73+
for j := 0 to i - 1 do
74+
if List[j] > List[j + 1] then
75+
begin
76+
SwapElements(j, j + 1);
77+
Swapped := True;
78+
end;
79+
80+
if not Swapped then
81+
Break;
82+
end;
83+
end;
84+
85+
function FormatIntegerList(List: TIntegerList): string;
86+
var
87+
i: Integer;
88+
begin
89+
Result := '';
90+
for i := 0 to List.Count - 1 do
91+
begin
92+
if i > 0 then
93+
Result += ', ';
94+
Result += IntToStr(List[i]);
95+
end;
96+
end;
97+
98+
var
99+
RawInput: string;
100+
Numbers: TIntegerList;
101+
begin
102+
if ParamCount <> 1 then
103+
ShowUsage;
104+
105+
RawInput := ParamStr(1);
106+
Numbers := ParseIntegerList(RawInput);
107+
try
108+
if not IsSorted(Numbers) then
109+
BubbleSort(Numbers);
110+
111+
Writeln(FormatIntegerList(Numbers));
112+
finally
113+
Numbers.Free;
114+
end;
115+
end.
116+

0 commit comments

Comments
 (0)