Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Insertion Sort

Title: Insertion Sort Question: Insertion sort algorithm Answer: { Insertion Sort is an elementary sorting algorithm that performs fewer comparisons than Selection Sort in the average case, and is very efficient when the input is almost sorted. It works by repeatedly taking the next value from the unsorted portion of the array and inserting it into the already sorted portion of the array. } procedure InsertionSort(Items: TStrings); var i, Position, n: integer; Value: string; Done : boolean; begin n := Items.Count; for i := 1 to n - 1 do begin Value := Items[i]; Position := i; Done := false; while not done do begin if Position Done := true else if Value = Items[Position - 1] then Done := true else begin Items[Position] := Items[Position - 1]; Position := Position - 1; end; end; Items[Position] := Value; end; end;