Merge sort
Në shqip: Renditja me bashkim
ShpjegimiSQ
Merge sort e ndan listën përgjysmë vazhdimisht derisa çdo pjesë ka një element, pastaj i bashkon pjesët e renditura dy nga dy. Gjithmonë O(n log n) dhe e qëndrueshme — shembulli klasik i „ndaj dhe sundo“.
EnglishEN
Merge sort keeps splitting the list in half until each piece has one item, then merges the sorted pieces two by two. Always O(n log n) and stable — the classic example of “divide and conquer”.
Si ta mendosh
Si dy mësues që secili rendit gjysmën e fletëve të provimit, dhe pastaj i bashkojnë duke marrë gjithmonë më të voglën nga të dy grumbujt.
Lexoje në anglisht
Like two teachers each sorting half the exam papers, then merging them by always taking the smaller from the two piles.
Shembull kodipython
def merge_sort(v):
if len(v) <= 1: return v
a, b = merge_sort(v[:len(v) // 2]), merge_sort(v[len(v) // 2:])
return [(a if a and (not b or a[0] <= b[0]) else b).pop(0)
for _ in range(len(a) + len(b))]