Python筆記 之 分治法求陣列最大子陣列

2021-10-09 10:30:09 字數 3117 閱讀 7854

演算法的最壞執行時間表示為:2t(

n/2)

+θ(n

)2t(n/2)+\theta(n)

2t(n/2

)+θ(

n)記作:θ(n

lg⁡n)

\theta(n\lg)

θ(nlgn)

'''

find_max_crossing_subarray(a,low,mid,hith)

sumleft=-∞

sum=0

for i=mid downto low

sum=sum+a[i]

if sum>sumleft

sumleft=sum

maxleft=i

sumright=-∞

sum=0

for j=mid+1 to hith

sum=sum+a[j]

if sum>sumright

sumright=sum

maxright=j

return(maxleft,maxright,sumleft+sumright)

'''

'''

find_max_subarray(a,low,high)

if low==hith

return(low,high,a[low])

else mid=(low+high)//2

(leftlow,lefthigh,leftsum)=

find_max_subarray(a,low,mid)

(rightlow,righthigh,rightsum)=

find_max_subarray(a,mid+1,high)

(crosslow,crosshigh,crosssum)=

find_max_crossing_subarray(a,low,mid,high)

if leftsum>=rightsum and leftsum>=crosssum

return (leftlow,lefthigh,leftsum)

elseif rightsum>=leftsum and rightsum>=crosssum

return (rightlow,righthigh,rightsum)

else

return (crosslow,crosshigh,crosssum)

'''

def

find_max_crossing_subarray

(a,low,mid,high)

:'''

a是乙個包含負數的列表

合併演算法是要返回乙個跨越分割店mid的最大陣列

'''sumleft=

float

("-inf"

) s=

0for i in

range

(mid,-1

,-1)

: s+=a[i]

if s>sumleft:

sumleft=s

maxleft=i

sumright=

float

("-inf"

) s=

0for j in

range

(mid+

1,high+1)

: s+=a[j]

if s>sumright:

sumright=s

maxright=j

return

(maxleft,maxright,sumleft+sumright)

def

find_max_subarray

(a,low,high)

:'''

a是乙個包含負數的列表

low代表列表a的最小下標,high代表最大下標

函式返回a所包含的最大連續陣列

'''if low==high:

return

(low,high,a[low]

)else

: mid=

(low+high)//2

(leftlow,lefthigh,leftsum)

=find_max_subarray(a,low,mid)

(rightlow,righthigh,rightsum)

=find_max_subarray(a,mid+

1,high)

(crosslow,crosshigh,crosssum)

=find_max_crossing_subarray(a,low,mid,high)

if leftsum>=rightsum and leftsum>=crosssum:

return

(leftlow,lefthigh,leftsum)

elif rightsum>=leftsum and rightsum>=crosssum:

return

(rightlow,righthigh,rightsum)

else

:return

(crosslow,crosshigh,crosssum)

a=[13

,-3,

-25,20

,-3,

-16,-

23,18,

20,-7

,12,-

5,-22

,15,-

4,7]

print

(a)low,high,

sum=find_max_subarray(a,0,

len(a)-1

)print

(low,high,

sum)

print

(a[low:high+1]

)[13,

-3,-

25,20,

-3,-

16,-23

,18,20

,-7,

12,-5

,-22,

15,-4

,7]7

1043[18

,20,-

7,12]

分治法求陣列中的眾數

先說一下題目吧,很簡單,就是給一組陣列,求陣列中的眾數,但是要用分治法。首先是要運用快排的分割演算法,設函式名為quick,重複次數設定為n,眾數設為mode,陣列長度即為length.c 實現的 如下 includeusing namespace std 全域性變數儲存重數 int n 0 全域性...

分治法求陣列最大最小值

常規的做法是遍歷一次,分別求出最大值和最小值,但我這裡要說的是分治法 divide and couquer 將陣列分成左右兩部分,先求出左半部份的最大值和最小值,再求出右半部份的最大值和最小值,然後綜合起來求總體的最大值及最小值。這是個遞迴過程,對於劃分後的左右兩部分,同樣重複這個過程,直到劃分區間...

凸包問題之分治法

凸包 按橫座標排序,以最小點與最大點之間的連線為準,在直線一側找使三角形面積最大的點,此點必在凸包內,以找到點與最大點或最小點繼續遞迴以尋找最大三角形面積尋找凸包點,直至找不到符合條件的點。實現 如下 include include include define max size 10001 str...