Saralashni birlashtirish Biz butun sonlarni massiviga saralashni amalga oshiramiz


Download 16.61 Kb.
Sana06.05.2020
Hajmi16.61 Kb.
#103609
Bog'liq
Merge Sort 1


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
Download 16.61 Kb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling