From Clomosy Docs
Bubble sort is one of the simplest sorting algorithms. In this comparison-based algorithm, each element in the list is compared with the element next to it.
If the value of the first element is greater than the value of the second element, the two elements are swapped.
Then, the values of the second and third elements are compared. If the value of the second element is greater than the value of the third element, these two elements are swapped, and this process continues until the entire list is sorted.
Example:
- TRObject Syntax
var
arr: array[0..6] of Integer;
i,j,n,temp : Integer;
str : string;
void bubbleSort;
{
n = Length(arr);
for (i = 0 to n - 2)
{
for (j = 0 to n - i - 2)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
{
arr[0] = 12;
arr[1] = 11;
arr[2] = 13;
arr[3] = 5;
arr[4] = 1;
arr[5] = 7;
arr[6] = 9;
str = 'Unordered array: ';
for (i = 0 to Length(arr)-1)
{
str = str + IntToStr(arr[i]) + ' ';
}
ShowMessage(str);
bubbleSort;
str = 'Array sorted from smallest to largest: ';
for (i = 0 to Length(arr)-1)
{
str = str + IntToStr(arr[i]) + ' ';
}
ShowMessage(str);
str = 'Array sorted from largest to smallest: ';
for (i = Length(arr)-1 downto 0)
{
str = str + IntToStr(arr[i]) + ' ';
}
ShowMessage(str);
}
- Base Syntax
var
arr: array[0..6] of Integer;
i,j,n,temp : Integer;
str : string;
procedure bubbleSort;
begin
n := Length(arr);
for i := 0 to n - 2 do
begin
for j := 0 to n - i - 2 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;
end;
begin
arr[0] := 12;
arr[1] := 11;
arr[2] := 13;
arr[3] := 5;
arr[4] := 1;
arr[5] := 7;
arr[6] := 9;
str := 'Unordered array: ';
for i := 0 to Length(arr)-1 do
begin
str := str + IntToStr(arr[i]) + ' ';
end;
ShowMessage(str);
bubbleSort;
str := 'Array sorted from smallest to largest: ';
for i := 0 to Length(arr)-1 do
begin
str := str + IntToStr(arr[i]) + ' ';
end;
ShowMessage(str);
str := 'Array sorted from largest to smallest: ';
for i := Length(arr)-1 downto 0 do
begin
str := str + IntToStr(arr[i]) + ' ';
end;
ShowMessage(str);
end;
- Output: