Previous topic | Next topic | Ada Home Page | Index

Selection sort

The idea behind selection sort is that to sort N items you make N passes through them.

  1. On the first pass you find the largest value, and then swap it with the last item. Thus the largest item is now in position N.
  2. On the second pass you scan through just the first N-1 entries. The largest of those items is swapped with the item in position N-1. Hence the largest item overall is now in the last position; the second largest item is now in the second last position.
  3. This process is repeated, with one item being placed in its correct location each time.
  4. After N passes, the entire collection of data is sorted.

A simple variation is to find the smallest item each time and put it at the front.

To sort into descending order, the largest item is found each time and moved to the front (this is the algorithm that is used in the examples which follow).


Example


Algorithm

        for outer in (list start..list end-1) loop
            highest := outer;         -- starting highest value
            for inner in (outer .. list end) loop
                if (list(inner) > list(highest) then
                    highest := inner  -- new highest value
                end if
            end loop
            swap list(highest) and list(outer)
        end loop


Code

        type num_array is array (INTEGER range <>) of integer;
        num: num_array(1..9):=(11,34,26,90,37,58,10,47,36);


        procedure selection_sort(sortarray: in out num_array) is
        
          highest: integer;
          temp   : integer;

        begin

          for outer in (sortarray'FIRST .. (sortarray'LAST-1)) loop
             highest := outer;

             for inner in (outer+1) .. sortarry'LAST loop
                if sortarray(inner) > sortarray(highest) then
                   highest := inner;                -- new highest
                end if;
             end loop;
             temp:= sortarray(highest);             -- swap elements
             sortarray(highest):=sortarray(outer);
             sortarray(outer):= temp;
          end loop;

        end selection_sort;


Previous topic | Next topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 21 Feb 96