您的位置:首页 > 编程语言 > Go语言

Algorithm: Find the maximum

2015-05-29 08:47 387 查看

Algorithm M

Algorithm M (Find the maximum). Given n elements X[1], X[2],…, X
, 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
. (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
;

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm find maximum