Code optimized and complexity decreased

This commit is contained in:
Mehdi ALAOUI 2017-04-10 13:49:01 +01:00
parent e01cf425bd
commit 08cbd113a4

View File

@ -15,19 +15,24 @@ def longestSub(ARRAY): #This function is recursive
return ARRAY
#Else
PIVOT=ARRAY[0]
LONGEST_SUB=[] #This array will contains the longest increasing sub array
for i in range(1,ARRAY_LENGTH): #For each element from the array (except the pivot),
if (ARRAY[i] < PIVOT): #if the element is smaller than the pivot, it won't figure on the sub array that contains the pivot
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ] #But it cas figure in an increasing sub array starting from this element
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY) #We calculate the longest sub array that starts from this element
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ): #And we save the longest sub array that begins from an element smaller than the pivot (in LONGEST_SUB)
isFound=False
i=1
LONGEST_SUB=[]
while(not isFound and i<ARRAY_LENGTH):
if (ARRAY[i] < PIVOT):
isFound=True
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ]
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
LONGEST_SUB = TEMPORARY_ARRAY
else:
i+=1
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ] #Then we delete these elements (smaller than the pivot) from the initial array
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY) #And we calculate the longest sub array containing the pivot (in TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ): #Then we compare the longest array between TEMPORARY_ARRAY and LONGEST_SUB
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ]
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
return TEMPORARY_ARRAY
else: #And we return the longest one
else:
return LONGEST_SUB
#Some examples