Modified To add the list merge system
This commit is contained in:
parent
8b42d43574
commit
82956d484e
|
|
@ -47,11 +47,17 @@ def send_to_goulag(input_list:list)-> list :
|
||||||
|
|
||||||
idx = 0
|
idx = 0
|
||||||
temp = []
|
temp = []
|
||||||
|
is_sorted = True
|
||||||
while True:
|
while True:
|
||||||
|
|
||||||
if not input_list:
|
if not input_list:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
if len(input_list)<=1:
|
||||||
|
return input_list
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
while idx < len(input_list) - 1:
|
while idx < len(input_list) - 1:
|
||||||
if input_list[idx] > input_list[idx + 1]:
|
if input_list[idx] > input_list[idx + 1]:
|
||||||
temp.append(input_list[idx + 1])
|
temp.append(input_list[idx + 1])
|
||||||
|
|
@ -66,16 +72,48 @@ def send_to_goulag(input_list:list)-> list :
|
||||||
|
|
||||||
idx = 0
|
idx = 0
|
||||||
# Loop para reinserir elementos de 'temp' na lista principal
|
# Loop para reinserir elementos de 'temp' na lista principal
|
||||||
while idx < len(input_list):
|
merge_two_sorted_lists_in_place(input_list,temp)
|
||||||
if temp and input_list[idx] > temp[0]:
|
|
||||||
# Inserção no meio da lista input_list[idx:idx] = temp é O(N) no pior caso
|
|
||||||
input_list[idx:idx] = temp
|
|
||||||
temp.clear()
|
|
||||||
break
|
|
||||||
idx += 1
|
|
||||||
if len(temp) == 0:
|
|
||||||
return input_list
|
|
||||||
|
|
||||||
if temp:
|
if temp:
|
||||||
input_list.extend(temp) # extend é O(k) onde k é o tamanho de temp
|
input_list.extend(temp) # extend é O(k) onde k é o tamanho de temp
|
||||||
temp.clear()
|
temp.clear()
|
||||||
|
|
||||||
|
for i in range(len(input_list) - 1):
|
||||||
|
if input_list[i] > input_list[i + 1]:
|
||||||
|
is_sorted = False
|
||||||
|
break
|
||||||
|
if is_sorted:
|
||||||
|
return input_list
|
||||||
|
|
||||||
|
def merge_two_sorted_lists_in_place(list1: list, list2: list) -> list:
|
||||||
|
|
||||||
|
if not list2:
|
||||||
|
return list1
|
||||||
|
if not list1:
|
||||||
|
list1.extend(list2)
|
||||||
|
list2.clear()
|
||||||
|
return list1
|
||||||
|
|
||||||
|
|
||||||
|
ptr1 = 0
|
||||||
|
ptr2 = 0
|
||||||
|
|
||||||
|
|
||||||
|
while ptr1 < len(list1) and ptr2 < len(list2):
|
||||||
|
if list1[ptr1] > list2[ptr2]:
|
||||||
|
|
||||||
|
list1.insert(ptr1, list2[ptr2])
|
||||||
|
|
||||||
|
ptr1 += 1
|
||||||
|
|
||||||
|
list2.pop(ptr2)
|
||||||
|
else:
|
||||||
|
|
||||||
|
ptr1 += 1
|
||||||
|
|
||||||
|
|
||||||
|
if list2:
|
||||||
|
list1.extend(list2)
|
||||||
|
list2.clear() # Esvazia list2
|
||||||
|
|
||||||
|
return list1
|
||||||
Loading…
Reference in New Issue