<commit_before>{% highlight python linenos %} 
def merge(l, r):
    result = []
    i = j = 0
    while i < len(l) and j < len(r):
        if l[i] < r[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(r[j])
            j += 1
    result += l[i:]
    result += r[j:]
    return result

def msort(a):
    if len(a) == 1:
        return a
    mid = len(a) / 2
    return merge(MS(a[:mid]), MS(a[mid:]))

array = [101, 50, 2, 43, 6, 100, 8, 20, 3, 15]
print msort(array)
{% endhighlight %}<commit_msg>Update 2015-01-23-merge-sort-python.md<commit_after>---
layout: post
title: Mergesort in python
---

Time complexity: O(n*log(n)) for any case.
Writing it in python takes only few lines:

{% highlight python linenos %}
def merge(l, r):
    result = []
    i = j = 0
    while i < len(l) and j < len(r):
        if l[i] < r[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(r[j])
            j += 1
    result += l[i:]
    result += r[j:]
    return result

def msort(a):
    if len(a) == 1:
        return a
    mid = len(a) / 2
    return merge(msort(a[:mid]), msort(a[mid:]))


array = [101, 50, 2, 43, 6, 100, 8, 20, 3, 15]
print array
print msort(array)
{% endhighlight %}
{'fraction_non_alphanumeric': 0.171021377672209, 'fraction_numerical': 0.04275534441805225, 'mean_word_length': 1.988179669030733, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4026201', 'n_tokens_mistral': 537, 'n_tokens_neox': 470, 'n_words': 143}