首页 > 编程语言 > 详细

算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-006BitonicMax

时间:2016-04-20 19:41:05      阅读:172      评论:0      收藏:0      [点我收藏+]

 

 1 package algorithms.analysis14;
 2 
 3 import algorithms.util.StdOut;
 4 import algorithms.util.StdRandom;
 5 
 6 /******************************************************************************
 7  *  Compilation:  javac BitonicMax.java
 8  *  Execution:    java BitonicMax N 
 9  *  Dependencies: StdOut.java
10  *
11  *  Find the maximum in a bitonic array (strictly increasing, then strictly
12  *  decreasing) of size N in log N time.
13  * 
14  *  % java BitonicMax N
15  *
16  ******************************************************************************/
17 
18 
19 public class BitonicMax {
20 
21     // create a bitonic array of size N
22     public static int[] bitonic(int N) {
23         int mid = StdRandom.uniform(N);
24         int[] a = new int[N];
25         for (int i = 1; i < mid; i++) {
26             a[i] = a[i-1] + 1 + StdRandom.uniform(9);
27         }
28 
29         if (mid > 0) a[mid] = a[mid-1] + StdRandom.uniform(10) - 5;
30 
31         for (int i = mid + 1; i < N; i++) {
32             a[i] = a[i-1] - 1 - StdRandom.uniform(9);
33         }
34 
35         for (int i = 0; i < N; i++) {
36             StdOut.println(a[i]);
37         }
38         return a;
39     } 
40 
41     // find the index of the maximum in a bitonic subarray a[lo..hi]
42     public static int max(int[] a, int lo, int hi) {
43         if (hi == lo) return hi;
44         int mid = lo + (hi - lo) / 2;
45         if (a[mid] < a[mid + 1]) return max(a, mid+1, hi);
46         if (a[mid] > a[mid + 1]) return max(a, lo, mid);
47         else return mid;
48     } 
49 
50 
51 
52     public static void main(String[] args) {
53 
54         int N = Integer.parseInt(args[0]);
55         int[] a = bitonic(N);
56         StdOut.println("max = " + a[max(a, 0, N-1)]);
57     }
58 }

 

算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-006BitonicMax

原文:http://www.cnblogs.com/shamgod/p/5413854.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!