Name Best-case Average-case Worst-case Memory Stable
MergeSort n log n n log n n log n worst: n yes

MergeSort


Your browser does not support the HTML5 canvas tag.

Java Code

public void mergeSort(int[] array, int l, int r) {
     if (l < r) {
          int m = (l + r) / 2;
          mergeSort( array , l , m );
          mergeSort( array , m + 1 , r );
          merge( array , l , m , r );
     }
}

public void merge(int[] array, int l, int m, int r) {
     int[] temp = array.clone();
     int left = l;
     int right = m + 1;
     int pos = left;

     while (left <= m || right <= r) {
          if (left <= m && right <= r) {
               if (temp[ left ] <= temp[ right ]) {
                    array[ pos ] = temp[ left ];
                    left++;
               } else {
                    array[ pos ] = temp[ right ];
                    right++;
               }
          } else if (left <= m) {
               array[ pos ] = temp[ left ];
               left++;
          } else if (right <= r) {
               array[ pos ] = temp[ right ];
               right++;
          }
          pos++;
     }
} 
            

How to use

Use the textfield to type in a number and add it by either pressing ENTER or by clicking on the "Add" button.
You can also add 10 random numbers at once by clicking on the "10 Random Keys" button. Overall you can add up to 50 keys.
The "Sort" button starts to sort the keys with the selected algorithm. Alternatively you can sort 100 random keys fast for a quick impression of how the algorithm works.