user4877975
user4877975

Reputation:

How do I find the index of the maximum value in an array?

Is there a built in function for that in Delphi 6? That is, a function to retrieve the index of the value returned by the MaxValue function.

If not what is the most efficient routine?

Upvotes: 1

Views: 2778

Answers (1)

David Heffernan
David Heffernan

Reputation: 613282

Delphi offers no such function, not in Delphi 6, and unless I am mistaken, not even in modern Delphi versions.

Without any information about the content of the array, you must check each element to find the maximum value, and the corresponding index.

uses
  Math; // MaxDouble is defined by this unit

function IndexOfMaxValue(const x: array of Double): Integer;
var
  Index: Integer;
  MaxValue: Double;
begin
  Result := -1;
  MaxValue := -MaxDouble;
  for Index := 0 to high(x) do begin
    if x[Index]>MaxValue then begin
      Result := Index;
      MaxValue := x[Index];
    end;
  end;
end;

Note that in the case of a tie, that is more than one element with the maximum value, this function will return the index of the first such element.

As @LURD points out, if all elements in the array are -MaxDouble then the function returns -1. That can be addressed like so:

function IndexOfMaxValue(const x: array of Double): Integer;
var
  Index: Integer;
  MaxValue: Double;
begin
  if high(x) = -1 then begin
    Result := -1;
  end else begin
    Result := 0;
    MaxValue := x[0];
    for Index := 1 to high(x) do begin
      if x[Index]>MaxValue then begin
        Result := Index;
        MaxValue := x[Index];
      end;
    end;
  end;
end;

Upvotes: 2

Related Questions