Previous topic | Next topic | Ada Home Page | Index

Linear search

Linear search, also known as sequential search, means starting at the beginning of the data and checking each item in turn until either the desired item is found or the end of the data is reached.

Algorithm

   For each item in the database
      if the item matches the wanted info
         exit with this item
   Continue loop
   wanted item is not in database

Linear search - code

There are two common forms of code for linear search. The difference is what is returned as the result of the search.

Return the data itself


        function findstudent (adfa:in adfaresults;  -- database
                              findname:in snames)   -- value sought
        return students 
        is

          empty:students;     -- null value, in case not found

        begin

          for division in adfa'RANGE loop
             for student in divresults'RANGE loop
              if (adfa(division)(student).detail.sname=findname)then
	            return adfa(division)(student);
              end if;
            end loop;
          end loop;

          return empty;

        end findstudent;

Return the location of the data


        ------------------------------------------------------
        --  search_car - search cars database for desired rego
        ------------------------------------------------------

        function search_car(c:Car_list; rego:String)
                         return NATURAL is

        begin -- search_car
            -- now look for the car with wanted rego
            for n in c'RANGE loop
                if c(n).reg_number = rego then
                    return n;                -- gotcha
                end if;
            end loop;
            return 0;                        -- out of luck
        end search_car;


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