Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Bubble Sort

Title: Bubble Sort Question: The Bubble Sort algorithm Answer: { Bubble Sort Bubble Sort is very! inefficient but a good way to understand more difficult sorting algorithms such as insertion sort. Bubble Sort works by repeatedly scanning the array, checking adjacent pairs of values to see if they are in the proper order. Whenever a pair of values is found to be out of order, they are interchanged and done is set to false, to indicate the array must be scanned again. This procedure will end when the array is scanned and all adjacent values are in their proper sorted order. } procedure BubbleSort(Items: TStrings); var done: boolean; i, n: integer; Dummy: string; begin n := Items.Count; repeat done := true; for i := 0 to n - 2 do if Items[i] Items[i + 1] then begin Dummy := Items[i]; Items[i] := Items[i + 1]; Items[i + 1] := Dummy; done := false; end; until done; end;