• 查找数组中最大子数组C语言实现


          一个数组,查找这个数组中最大的一个连续子数组。比如{1, 2, 3, –11},这个数组中最大子数组为{1, 2, 3}。

         算法复杂度: O(nlgn)

          伪代码:

    image

    image

          C代码:

    #include <stdio.h>
    
    typedef struct index {
    	int left;
    	int right;
    	int sum;
    } index_t;
    
    index_t find_max_crossing_subarray(int* a, int low, int mid, int high)
    {
    	int left_sum = 0x80000000;
    	int right_sum = 0x80000000;
    	int sum = 0;
    	int max_left, max_right;
    
    	int i;
    
    	index_t value;
    
    	for (i = mid; i >= low; i--) {
    		sum += a[i];
    		if (sum > left_sum) {
    			left_sum = sum;
    			max_left = i;
    		}
    	}
    
    	sum = 0;
    	for (i = mid + 1; i <= high; i++) {
    		sum += a[i];
    		if (sum > right_sum) {
    			right_sum = sum;
    			max_right = i;
    		}
    	}
    
    	value.left = max_left;
    	value.right = max_right;
    	value.sum = left_sum + right_sum;
    
    	return value;
    }
    
    index_t find_maximum_subarray(int *a, int low, int high)
    {
    	index_t left_value, right_value, value;
    	int mid;
    
    	if (high == low) {
    		value.left = low;
    		value.right = high;
    		value.sum = a[low];
    		return value;
    	} else {
    		mid = (high + low)/2;
    		left_value = find_maximum_subarray(a, low, mid);
    		right_value = find_maximum_subarray(a, mid + 1, high);
    		value = find_max_crossing_subarray(a, low, mid, high);
    
    		if (left_value.sum >= right_value.sum && left_value.sum >= value.sum)
    			return left_value;
    		else if (right_value.sum >= left_value.sum && right_value.sum >= value.sum)
    			return right_value;
    		else 
    			return value;
    	}
    }
    
    int main()
    {
    	int a[] = {3, 8, -1, -6, 12, 34, -43, 28};
    
    	index_t value;
    
    	value = find_maximum_subarray(a, 0, 7);
    
    	printf("The maximum subarray is from %d to %d, sum is %d\n", value.left, value.right, value.sum);
    
    	return 0;
    }
  • 相关阅读:
    java抽象类怎么实例化了及C++中抽象类的构造函数
    树及其遍历
    C++中类的多态与虚函数的使用
    C++中#if #ifdef 的作用
    用链表实现两大数相乘
    C++中的链表类的设计
    IPicture总结
    c++标准库中,含有链表的类list
    TCP/IP、Http的区别
    C语言单链表实现19个功能完全详解
  • 原文地址:https://www.cnblogs.com/wangshuo/p/2163526.html
Copyright © 2020-2023  润新知