1 /** 2 * 在一组数字当中,在尽可能小的比较此处的前提下,获取最大值和最小值 3 * @author JimmyPC 4 * 5 */ 6 public class Problem_MinMax { 7 8 public class Node { 9 public int min; 10 public int max; 11 } 12 //获取最大最小值 13 public Node getMinMax(int a[],int n){ 14 Node minmax = new Node(); 15 int i; 16 if(n%2 ==0){ 17 if(a[0] >a[1]){ 18 minmax.max = a[0]; 19 minmax.min = a[1]; 20 }else{ 21 minmax.max = a[1]; 22 minmax.min = a[0]; 23 } 24 i = 2; 25 }else{ 26 minmax.max = a[0]; 27 minmax.min = a[0]; 28 i = 1; 29 } 30 31 while(i < n-1){ 32 if(a[i] > a[i+1]){ 33 if(a[i] > minmax.max){ 34 minmax.max = a[i]; 35 } 36 if(a[i+1] < minmax.min){ 37 minmax.min = a[i+1]; 38 } 39 }else{ 40 if(a[i+1] > minmax.max){ 41 minmax.max = a[i+1]; 42 } 43 if(a[i] < minmax.min){ 44 minmax.min = a[i]; 45 } 46 } 47 i+= 2; 48 } 49 return minmax; 50 } 51 52 /** 53 * @param args 54 */ 55 public static void main(String[] args) { 56 int arr[] = {1000, 11, 445, 1, 330, 3000}; 57 int arr_size = 6; 58 Node minmax = new Problem_MinMax().getMinMax( 59 arr, arr_size); 60 System.out.println("Minimum element is " + minmax.min); 61 System.out.println("Maximum element is " + minmax.max); 62 63 } 64 } 参考:http://blog.csdn.net/jiyanfeng1/article/details/8541886,http://www.geeksforgeeks.org/maximum-and-minimum-in-an-array/
时间: 2024-11-10 00:09:41