Skip to content

Instantly share code, notes, and snippets.

@ka8725
Last active December 26, 2015 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ka8725/4fbf68c66e274b9d7290 to your computer and use it in GitHub Desktop.
Save ka8725/4fbf68c66e274b9d7290 to your computer and use it in GitHub Desktop.
The merge sort algorithm implemented in Erlang
msort([]) ->
[];
msort([H|[]]) ->
[H];
msort(List) ->
[H|L] = divide2(List),
msort(msort(H), msort(L)).
msort(List1, List2) ->
msort(List1, List2, []).
msort([H1|L1], [H2|L2], Acc) when H1 < H2 ->
msort(L1, [H2|L2], [H1|Acc]);
msort([H1|L1], [H2|L2], Acc) when H2 =< H1 ->
msort([H1|L1], L2, [H2|Acc]);
msort([H1|L1], [], Acc) ->
msort(L1, [], [H1|Acc]);
msort([], [H2|L2], Acc) ->
msort([], L2, [H2|Acc]);
msort([], [], Acc) ->
reverse(Acc).
@ka8725
Copy link
Author

ka8725 commented Dec 26, 2015

def mergeSort(alist):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment