1. 程式人生 > >《演算法導論》學習---尋找最大子陣列

《演算法導論》學習---尋找最大子陣列

#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<vector>

using namespace std;

struct MyStruct
{
	int low=0;
	int high=0;
	int sum=0;
};
//這個函式尋找跨域mid的最大子陣列
MyStruct find_cross(int a[],int low,int high,int mid)
{
	int l_sum=-100000, r_sum=-100000;//左邊最大,右邊最大,這裡應該取負無窮s
	int sum=0;//記錄左右的和
	MyStruct res;
	for (int i = mid; i >= low; i--)
	{
		sum += a[i];
		if (sum > l_sum)
		{
			l_sum = sum;
			res.low = i;
		}
	}
	sum = 0;
	for (int i = mid+1; i <= high; i++)
	{
		sum += a[i];
		if (sum > r_sum)
		{
			r_sum = sum;
			res.high = i;
		}
	}
	res.sum = l_sum + r_sum;
	return res;
}

MyStruct find(int a[], int low, int high)
{
	int mid;
	MyStruct res;
	MyStruct left_sum, right_sum, cross_sum;
	if (low == high)
	{
		res.low = low;
		res.high = high;
		res.sum = a[low];
		return res;
	}
	else
	{
		mid = (low + high) / 2;
		left_sum = find(a, low, mid);//找到左邊的最大子陣列
		right_sum = find(a, mid + 1, high);//找到右邊的最大子陣列
		cross_sum = find_cross(a, low, high, mid);//找到跨越mid的最大子陣列
	}
	//返回三者最大的
	if (left_sum.sum > right_sum.sum)
	{
		if (left_sum.sum > cross_sum.sum)
		{
			return left_sum;
		}
		else
		{
			return cross_sum;
		}
	}
	else
	{
		if (right_sum.sum > cross_sum.sum)
		{
			return right_sum;
		}
		else
		{
			return cross_sum;
		}
	}
}


int main()
{
	MyStruct res;
	int a[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
	res = find(a, 0, 15);
	cout << res.low << "+" << res.high << "+" << res.sum << endl;
	system("pause");
}

執行結果

7+10+43