Saralashni birlashtirish
Biz butun sonlarni massiviga saralashni amalga oshiramiz
Oddiy qismdan boshlaylik. Algoritmning asosiy g'oyasi - massivlarni yarmiga bo'lish va ularni rekursiv ravishda tartiblash. Biz buni iloji boricha davom ettiramiz, ya'ni bitta elementga ega subarrayslarni qo'lga kiritmagunimizcha:
import operator
def merge_sort(L, compare=operator.lt):
if len(L) < 2:
return L[:]
else:
middle = int(len(L) / 2)
left = merge_sort(L[:middle], compare)
right = merge_sort(L[middle:], compare)
return merge(left, right, compare)
Oxirgi usul qo'ng'iroq
merge
saralashni boshlashdan oldin barcha bo'linishlar bo'lishiga kafolat beramiz. Funktsiya yarating merge():
def merge(left, right, compare):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append (left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
Do'stlaringiz bilan baham: |