Data Structures and Algorithms

Mergesort

Quicksort is akin to dividing a file into two parts

  • smallest elements
  • largest elements
Algorithm quicksort(array)
    partition(array)
    quicksort(lefthalf)
    quicksort(righthalf)

Mergesort is akin to combining two ordered files into one larger ordered file

Algorithm mergesort(array)
    mergesort(lefthalf)
    mergesort(righthalf)
    merge(lefthalf, righthalf)

Important concerns for sorting

This was made for sorting things on magnetic tapes. And the thing about magnetic tapes was that they were not good for random access. Items are accessed sequentially or in large blocks. You need enough memory for at least one thing while sorting.

void merge(Item c[], Item a[], int size_a, Item b[], int size_b) {
    for (int i = 0, j = 0, k = 0; k < size_a + size_b; k++) {
        if (i == size_a)
            c[k] = b[j++];
        else if (j == size_b)
            c[k] = a[i++];
        else
            c[k] = (a[i] <= b[j]) ? a[i++] : b[j++];
    }
}

The runtime of this is , where is the size of A plus the size of B.

Qualities of Mergesort

Advantages:

  • Fast: all the time
  • Stable (if merge is stable)
  • Good for accessing things sequentially

Disadvantages:

  • Best case performance
  • $$\Theta(N) additional memory$