public static void main(String[] args) {
int[] datas = new int[5];
datas[0] = 2;
datas[1] = 3;
datas[2] = 1;
datas[3] = 5;
datas[4] = 4;
int maxIndex = 0; // 위치
int max = 2; // 값
for (int i = 1; i < datas.length; i++) {
if (max < datas[i]) {
max=datas[i];
maxIndex = i;
}
}
System.out.printf("maxIdx: %d, maxNum: %d\n", maxIndex, max);
/*
* maxIndex max i i<5 max<datas[i]
* ===========================================================
* 0 2 1 T T
* 1 3 2 T F
* 3 T T
* 3 5 4 T F
* 5 F
* */
}
위에 코드를 아래와 같이 단순화할 수 있다
`maxIndex`만 알면 최대값을 알 수 있기 때문!
public static void main(String[] args) {
int[] datas = new int[5];
datas[0] = 2;
datas[1] = 3;
datas[2] = 1;
datas[3] = 5;
datas[4] = 4;
int maxIndex = 0; // 위치
for (int i = 1; i < datas.length; i++) {
if (datas[maxIndex] < datas[i]) {
maxIndex = i;
}
}
System.out.printf("maxIdx: %d, maxNum: %d\n", maxIndex, datas[maxIndex]);
/*
* maxIndex i i<5 datas[maxIndex]<datas[i]
* ====================================================================
* 0 1 T T
* 1 2 T F
* 3 T T
* 3 4 T F
* 5 F
* */
}
'-- 기타 -- > IT KOREA 국비 지원 강의' 카테고리의 다른 글
[알고리즘] 버블 정렬 코드 리팩토링 (1) | 2023.11.27 |
---|---|
[이클립스] Open Associated Perspective 안내창 (0) | 2023.11.27 |
[알고리즘] 이진 탐색 (0) | 2023.11.24 |
별찍기를 해보자 (1) | 2023.11.22 |
[1일차] 주관적인 키워드 정리 (0) | 2023.11.21 |