Delphi Programming

Bubble sort

2,919pages on
this wiki
Add New Page
Talk2 Share

Bubble sort algorithm example from TThread demo of Delphi 5:

Sorting an array of Integer:

procedure TBubbleSort.Sort(var A: array of Integer);
  I, J, T: Integer;
  for I := High(A) downto Low(A) do
    for J := Low(A) to High(A) - 1 do
      if A[J] > A[J + 1] then
        VisualSwap(A[J], A[J + 1], J, J + 1);
        T := A[J];
        A[J] := A[J + 1];
        A[J + 1] := T;
        if Terminated then Exit;

Sorting a TStringList ( It's recommended that you use the TStringList.Sort procedure, since it is a Quicksort implementation which is faster):

function BubbleSort( list: TStringList ): TStringList;
  i, j: Integer;
  temp: string;
  // bubble sort
  for i := 0 to list.Count - 1 do begin
    for j := 0 to ( list.Count - 1 ) - i do begin
      // Condition to handle i=0 & j = 9. j+1 tries to access x[10] which
      // is not there in zero based array
      if ( j + 1 = list.Count ) then
      if ( list.Strings[j] > list.Strings[j+1] ) then begin
        temp              := list.Strings[j];
        list.Strings[j]   := list.Strings[j+1];
        list.Strings[j+1] := temp;
      end; // endif
    end; // endwhile
  end; // endwhile
  Result := list;
Code Snippets
DatabasesFiles and I/OForms/WindowsGraphicsNetworkingMath and AlgorithmsMiscellaneousMultimediaSystemVCL

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.