2010. szeptember 23., csütörtök

Selection Sort


Problem/Question/Abstract:

Selection sort algorithm

Answer:

Selection Sort

An elementary sorting algorithm that is designed to minimize the number of exchanges that are performed. It works by making n-1 passes over the unsorted portion of the array, each time selecting the largest value. This value is then moved into its final sorted position with a single exchange.

procedure SelectionSort(Items: TStrings);
var
  i, n, maxIndex, topIndex: integer;
  Dummy: string;
begin
  n := Items.Count;

  for topIndex := n - 1 downto 1 do
  begin
    maxIndex := topIndex;
    for i := 0 to topIndex - 1 do
      if Items[i] > Items[maxIndex] then
        maxIndex := i;

    Dummy := Items[topIndex];
    Items[topIndex] := Items[maxIndex];
    Items[maxIndex] := Dummy;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése