zoukankan      html  css  js  c++  java
  • divide-conquer-combine(4.1 from the introduction to algorithm)

    this example is from chapter 4 in 《the introduction to algorithm》

    the main idea is all showed in the book , i think maybe realizing the algorithm is a good way to understand it.

    /*
    from : introduction to algorithm chapter four
    algorithm:divide and conquer
    the time complexity of this algorithm is O(n * logn)
    
    */
    #include <stdio.h>
    
    int Find_max_crossing_subarray(int *a, int low, int mid, int high)
    {
        int left_sum = -0xffff;
        int sum = 0;
        for (int i = mid; i >= low; i--)
        {
            sum += a[i];
            if (sum > left_sum)
                left_sum = sum;
        }
        int right_sum = -0xffff;
        sum = 0;
        for (int j = mid+1; j <= high; j++)
        {
            sum += a[j];
            if (sum > right_sum)
                right_sum = sum;
        }
        return left_sum + right_sum;
    }
    
    int find_maximum_subarray(int *a, int low, int high)
    {
        if (high == low)
        {
            return *(a+high); // base case: only one element
        }
        else
        {
            int mid = (high + low)/2;
            if ((find_maximum_subarray(a, low, mid) >= find_maximum_subarray(a, mid+1, high))&&(find_maximum_subarray(a, low, mid)>=Find_max_crossing_subarray(a,low,mid,high)))
            {
                return find_maximum_subarray(a, low, mid);
            }
            else if ((find_maximum_subarray(a, mid+1, high) >= find_maximum_subarray(a, low, mid))&&(find_maximum_subarray(a, mid+1, high) >= Find_max_crossing_subarray(a,low,mid,high)))
            {
                return find_maximum_subarray(a, mid+1, high);
            }
            else
            {
                return Find_max_crossing_subarray(a, low, mid, high);
            }
        }
    }
    
    int main()
    {
        int a[16]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
        int b[6]={1,2,3,4,5};
        printf("%d
    ",find_maximum_subarray(a,0,15));
        printf("%d
    ",find_maximum_subarray(b,0,5));
    }
  • 相关阅读:
    使用replaceAll替换“/”为“/”
    如何在Lucene里面进行数字范围搜索 (Numeric Range Query)
    Java中的参数传递
    安装配置WordPress 3.0的多站点功能
    Apache Hadoop 项目介绍
    Java中的Set操作
    使用Desktop API in Java SE 6打开文件或者网页
    Java集合(转帖)
    数据结构牛客网习题纠错130
    PAT 1045 Favorite Color Stripe[dp][难]
  • 原文地址:https://www.cnblogs.com/maverick-fu/p/3986663.html
Copyright © 2011-2022 走看看