欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

查找数组中最大值java

程序员文章站 2022-05-12 10:41:31
...
package interview;

/*
 * 数组元素先升后降找出最大值
 */

public class FirstAESCLastDESC {

	
	public static void main(String[] args) {
		int[] arrays = {1,2,5,9,5,4};
		System.out.println(arrays[searchMax(arrays)]);
	}
	
	public static int searchMax(int[] arrays) {
		int len = arrays.length;
		int begin = 0;
		int end=len-1;
		int mid = (len-begin)/2;
		
		while(mid>0&&mid<len-1) {
			if(arrays[mid] > arrays[mid+1]&& arrays[mid]>arrays[mid-1]) {
				return mid;
			}else if(arrays[mid]<arrays[mid+1]) {
				begin = mid+1;
				mid = (end-begin)/2;
			}else {
				end = mid-1;
				mid = (end-begin)/2;
			}
		}
		return -1;
		
	}
}