Algorithm M
Algorithm M (Find the maximum). Given n elements X[1], X[2],…, X[n], we
will find m and j such that m = X[j] = max1<=i<=nX[i], where j is the largest
index that satisfies this relation.
M1. [Initialize.] Set j <– n, k <– n-1, m <– X[n]. (During this algorithm we
will have m = X[j] = maxk< i<=nX[i].)
M2. [All tested?] If k = 0, the algorithm terminates.
M3. [Compare.] If X[k] <= m, go to M5.
M4. [Change m.] Set j <– k, m <– X[k]. (This value of m is a new current
maximum.)
M5. [Decrease k.] Decrease k by one and return to M2. |
Flow diagram
Java program
/**
* Created with IntelliJ IDEA.
* User: 1O1O
* Date: 12/17/13
* Time: 6:52 PM
* :)~
* Find the maximum:ALGORITHMS
*/
public class Main {
public static void main(String[] args) {
int N = 16;
int[] X = new int[17];
X[1] = 503;
X[2] = 87;
X[3] = 512;
X[4] = 61;
X[5] = 908;
X[6] = 170;
X[7] = 897;
X[8] = 275;
X[9] = 653;
X[10] = 426;
X[11] = 154;
X[12] = 509;
X[13] = 612;
X[14] = 677;
X[15] = 765;
X[16] = 703;
int j=N;
int k=N-1;
int m=X[N];
while (k > 0){
if(X[k] > m){
j=k;
m=X[k];
}
k--;
}
System.out.println("Max: m=X[j]="+"X["+j+"]="+m);
}
}
Outputs
Max: m=X[j]=X[5]=908
Reference
<< The Art of Computer Programming: Fundamental Algorithms>> VOLUME 1, DONALD E. KNUTH