Seed7 
 FAQ 
 Manual 
 Screenshots 
 Examples 
 Algorithms 
 Download 
 Links 

 Algorithms 
 Sorting 
 Searching 
 Date & Time 
 String 
 Mathematics 
 File 
 Puzzles 
 Others 
 Algorithms 
Searching
 previous   up   next 

Recursive binary search in an array

const func integer: binarySearch (in array elemType: arr, in elemType: aKey, in integer: low, in integer: high) is func
  result
    var integer: result is 0;
  begin
    if low <= high then
      result := (low + high) div 2;
      if aKey < arr[result] then
        result := binarySearch(arr, aKey, low, pred(result)); # search left
      elsif aKey > arr[result] then
        result := binarySearch(arr, aKey, succ(result), high); # search right
      end if;
    end if;
  end func;

const func integer: binarySearch (in array elemType: arr, in elemType: aKey) is
  return binarySearch(arr, aKey, 1, length(arr));

Iterative binary search in an array

const func integer: binarySearch2 (in array elemType: arr, in elemType: aKey) is func
  result
    var integer: result is 0;
  local
    var integer: low is 1;
    var integer: high is 0;
    var integer: middle is 0;
  begin
    high := length(arr);
    while result = 0 and low <= high do
      middle := low + (high - low) div 2;
      if aKey < arr[middle] then
        high := pred(middle);
      elsif aKey > arr[middle] then
        low := succ(middle);
      else
        result := middle;
      end if;
    end while;
  end func;

Linear search in an array

const func integer: linearSearch (in array elemType: arr, in elemType: aKey) is func
  result
    var integer: result is 0;
  begin
    result := length(arr);
    while result >= 1 and arr[result] <> aKey do
      decr(result);
    end while;
  end func;

Find the minimum element in an array

const func integer: findMinIndex (in array elemType: arr) is func
  result
    var integer: minIndex is 0;
  local
    var integer: index is 0;
    var elemType: minValue is elemType.value;
  begin
    minValue := arr[1];
    for index range 2 to length(arr) do
      if arr[index] < minValue then
        minIndex := index;
        minValue := arr[index];
      end if;
    end for;
  end func;

Find the maximum element in an array

const func integer: findMaxIndex (in array elemType: arr) is func
  result
    var integer: maxIndex is 1;
  local
    var integer: index is 0;
    var elemType: maxValue is elemType.value;
  begin
    maxValue := arr[1];
    for index range 2 to length(arr) do
      if arr[index] > maxValue then
        maxIndex := index;
        maxValue := arr[index];
      end if;
    end for;
  end func;


 previous   up   next