最大値の取得(java)
ゲスト
ゲスト
ATOMRSS
  • コード求むID: 358
  • 登録日時:  2008/12/10 13:48
  • 最終更新日時: 2008/12/16 03:28
  • アクセス数: 1860
  • タグ: 
  • codeなにがしブックマークに追加する 0 users
  • このページを del.icio.us に追加
  • このページをはてなブックマークに追加

x[i]に多量の数値の配列を行い,
その最大値を表示したいのですが,
最大値の取得について教えていただけませんか?

コメント

  • ゲスト
  • 1:ゲスト
  • 2008/12/10 15:33

ソートでググれ

GJGJ

配列の中身を変更していいなら、Arraysクラスの
sortメソッドを使うのが一番単純だと思いますが…。

GJGJ

  • ゲスト
  • 4:ゲスト (BLUEPIXY)
  • 2008/12/12 05:16

import java.util.Vector;

class VectorMax {

    public static void main(String args[]){
        Vector<Integer> vi = new Vector<Integer>();
        vi.add(10);
        vi.add(20);
        vi.add(33);
        vi.add(-1);
        vi.add(22);
        Integer max=vi.firstElement();//仮の最大
        for(Integer c : vi){
            if(c > max){
                max = c;
            }
        }
        System.out.println("max:"+max);
    }
}
みたいな・

GJGJ

import java.util.Arrays;

public class SortTest {
	public static void main(String[] args){
		double[] array = {1,5,3,2,4};
		double[] copied = Arrays.copyOf(array,array.length);
		Arrays.sort(copied);
		System.out.println(copied[copied.length-1]); // 最大値の表示
	}
}
Java 6.0以降ならこれでいけます。

GJGJ

  • ゲスト
  • 6:ゲスト
  • 2008/12/15 04:48

最大値を探すのにソートするのは、ばかげてない?

GJGJ


public class Moge {

	public static void main(String[] args) {
		int[] a = {1,5,2,3,6,4};
		System.out.println(Moge.max(a)); //output '6'
	}
	
	public static int max(int[] a){
		return Moge._max(a, 0, a[0]);
	}
	
	private static int _max(int[] a, int ind, int max){
		if(a.length-1 == ind) return max;
		return Moge._max(a, ind+1, Math.max(a[ind], a[ind+1]));
	}
}

あまりスマートでは無いですが。。

GJGJ

  • ゲスト
  • 8:ゲスト
  • 2008/12/15 16:02

>>6
アルゴリズムでググれ

GJGJ

  • ゲスト
  • 9:ゲスト
  • 2008/12/15 20:03

>>8
意味ない・

GJGJ

  • ゲスト
  • 10:ゲスト (BLUEPIXY)
  • 2008/12/16 03:28

ベクターとかCollection を使ってるなら
import java.util.Collections;
Integer max=Collections.max(vi);
でよい。

GJGJ

前へ 1 次へ

プレゼン公開・共有サイト handsOut.jp チーム・マイナス6% - みんなで止めよう温暖化

ブックマークコメント