分治演算法(一) 》陣列中的最小值最大值

2021-08-31 10:52:39 字數 676 閱讀 6095

問題:《程式設計之美》page166. 尋找陣列中的最大值,最小值。

public class minmax ;

int result=find(array);

system.out.println("min is " + result[0]+", max is " + result[1]);

result=merge(array,0,array.length-1);

system.out.println("min is " + array[result[0]]+", max is " + array[result[1]]);

}/*演算法設計:直接比較,需要比較2n次

*/ public static int find(int array)

int result=new int[2];

result[0]=min;

result[1]=max;

return result;

}/*演算法設計:分治方法比較。類似比賽中的淘汰賽,最後勝出者一定是最好的。兩兩相比,取其小(大)者,再互相比較,z比較次數:1.5n-2。

*/ public static int merge(int array, int start, int end)else

return result;

}}

最大值 最小值

求最大最小的時候有點小技巧,就是我們兩個兩個的比較,把大個跟當前最大比較,小的跟當前最小的比較,這樣就會節約一點比較時間,有原來的2 n到3 n 2。include include 得到最大最小值 int getmaxmin int ndata,int nlen,int pnmax,int pnmi...

陣列取最大值最小值

1 陣列取出最大值,最小值的方式 第一種 遍歷一邊陣列就可以找出需要的值,基本上可以說是速度最快的演算法,還不需要排序 int intarray int max intarray 0 int min intarray 0 for int i intarray listl arrays.aslist ...

獲取陣列中的最大值,最小值

使用索引的方式獲取 方法1 求最大值 最小值 public static void arrdemo4 假設最大值所在的索引是0 int maxindex 0 int minindex 0 for int i 1 i sort.length i if sort minindex sort i syst...