Thursday, 27 April 2017

Insertion Merge Sort

Insertion sort complexity - O(cn2) where c is a constant 
Merge sort having the complexity O(anlogn where a is constant) is better than insertion sort. 

However c < a, making insertion sort perform better than merge sort when n is smaller.
Hence, many implement sorting algo as a combination of both sorts to achieve better performance. Java uses this implementation.

Implementation of InsertionSort - 
public class InsertionSort {
    public static void sort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int x = array[i];
            int j = i - 1;
            for (; j >= 0; j--) {
                if (x < array[j]) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
            }
            array[j + 1] = x;
        }
    }
}

Implementation of InsertionSort - 
public class MergeInsertionSort {
    int[] arr;

    public MergeInsertionSort(int[] arr) {
        this.arr = arr;
    }

    public void mergeSort() {
        int p = 0;
        int r = arr.length - 1;
        int q = arr.length / 2;
        mergeSort(p, q, r);
    }

    private void mergeSort(int p, int q, int r) {
        if (r - p + 1 < 8) {
            insertionSort(p, r);
        } else {
            mergeSort(p, (q - p) / 2, q - 1);
            mergeSort(q, (r - q + 1) / 2, r);
            merge(p, q, r);
        }
    }

    private void merge(int p, int q, int r) {
        int temp = p;
        int tempQ = q;
        int a[] = new int[r - p + 1];
        for (int i = 0; i < a.length; i++) {
            if (p < tempQ && arr[p] < arr[q]) {
                a[i] = arr[p++];
            } else if (q <= r) {
                a[i] = arr[q++];
            }
        }
        for (int i = 0; i < a.length; ) {
            arr[temp++] = a[i++];
        }
    }

    private void insertionSort(int p, int r) {
        for (int i = p + 1; i <= r; i++) {
            int x = arr[i];
            int j = i - 1;
            for (; j >= p; j--) {
                if (x < arr[j]) {
                    arr[j + 1] = arr[j];
                } else {
                    break;
                }
            }
            arr[j + 1] = x;
        }
    }
} 

No comments:

Post a Comment