Problem Description:
Given an array of integers, the starting position and end point of all the sub-arrays and the largest subarray in the given integer array are obtained;
Method One: Exhaustive each sub-array, the time complexity of O (N2);
Method Three: Time complexity is O (N); Please consult your own books;
Method Two:
Adopt the idea of divide and conquer:
First, divide the array from the middle (the split point) into two parts (and the largest sub-array either on its left, or on its right, or across the split point), first find the left and the largest subarray, and then the right and the largest sub-array,
It then asks for the largest sub-array that passes through the middle divider and
1#include <iostream>2 using namespacestd;3 structsub{//defines a sub-array starting point, ending with all its elements and4 intstart;5 intend;6 7 intsum;8 };9 TenSub Merge (Sub Sub1,intStartintEndintA[])// One { A intleftsum=0, rightsum=0, leftpos= (start+end)/2, rightpos= (start+end)/2+1, leftmax=-10000, rightmax=-10000; - - for(intI= (start+end)/2; i>=start;i--) the { -Leftsum+=a[i];//find the maximum array and the starting point - if(leftmax<leftsum) - { +leftpos=i; -leftmax=leftsum; + } A } at - for(intI= (start+end)/2; i<=end;i++) - { -rightsum+=A[i]; - if(rightmax<rightsum)//find the maximum array and end point - { inrightpos=i; -rightmax=rightsum; to } + } - the if(sub1.sum< (rightmax+Leftmax)) * { $sub1.start=LeftPos;Panax NotoginsengSub1.end=Rightpos; -Sub1.sum= (rightmax+Leftmax); the } + A returnsub1; the } +Sub Recursion (intStartintEndinta[]) - { $ Sub sub1,sub2; $ - if(start<end) - { theSub1=recursion (Start, (start+end)/2, A); -Sub2=recursion ((start+end)/2+1, End,a); Wuyi theSub1=sub1.sum>sub2.sum?sub1:sub2; - Wu returnmerge (sub1,start,end,a); - } About $Sub1.start=sub1.end=start; -sub1.sum=A[start]; - - returnsub1; A } + intMain () the { - inta[]={1,-5,9,8,-3,-6, One}; $ theSub Sub1=recursion (0,6, a); the thecout<<sub1.start<<" to"<<sub1.end<<"sum:"<<sub1.sum<<Endl; the - } in
Divide and conquer--the largest array and