Algorithm: Find the maximum

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值