码迷,mamicode.com
首页 > 其他好文 > 详细

algorithm@ O(3/2 n) time to findmaximum and minimum in a array

时间:2016-02-07 09:44:28      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

    public static int[] max_min(int[] a){
        //res[0] records the minimum value while res[1] records the maximal one.
        int res[] = new int[2];
        int n = a.length;
        if(n == 0)  {
            return res;
        }
        if(n == 1) {
            res[0] = res[1] = a[0];
        }
        
        int min, max;
        if(n%2 == 1) {
            res[0] = res[1] = a[0];
            
            for(int i=1; i<=n-2; i+=2) {
                if(a[i] < a[i+1]) {
                    min = a[i];
                    max = a[i+1];
                }
                else {
                    min = a[i+1];
                    max = a[i];
                }
                res[0] = Math.min(min, res[0]);
                res[1] = Math.max(max, res[1]);
            }
        }
        else {
            res[0] = Math.min(a[0], a[1]);
            res[1] = Math.max(a[0], a[1]);
            for(int i=2; i<=n-2; i+=2) {
                if(a[i] < a[i+1]) {
                    min = a[i];
                    max = a[i+1];
                }
                else {
                    min = a[i+1];
                    max = a[i];
                }
                res[0] = Math.min(min, res[0]);
                res[1] = Math.max(max, res[1]);
            }
        }
        
        return res;
    }

 

algorithm@ O(3/2 n) time to findmaximum and minimum in a array

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/5184550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!