Merge Sort

Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.

Merge sort first divides the array into equal halves and then combines them in a sorted manner.

Algorithm

Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.

  • Step 1 − if it is only one element in the list it is already sorted, return.
  • Step 2 − divide the list recursively into two halves until it can no more be divided.
  • Step 3 − merge the smaller lists into new list in sorted order.
void merge(vector<int> &arr, int leftLow, int leftHigh, int rightLow, int rightHigh) {
    int size = rightHigh - leftLow + 1;
    int left = leftLow, right = rightLow;

    vector<int> sorted(size, 0);
    for (int i=0; i < size; i++) {
        if (left > leftHigh) {
            sorted[i] = arr[right];
            right += 1;
        } else if (right > rightHigh) {
            sorted[i] = arr[left];
            left += 1;
        } else if (arr[left] <= arr[right]) {
            sorted[i] = arr[left];
            left += 1;
        } else {
            sorted[i] = arr[right];
            right += 1;
        }
    }

    for (int i=0; i < size; i++) {
        arr[leftLow + i] = sorted[i];
    }
}

void mergeSort(vector<int> &arr, int low, int high) {
    if (low >= high) return;

    int middle = low + (high - low)/2;
    mergeSort(arr, low, middle);
    mergeSort(arr, middle+1, high);
    merge(arr, low, middle, middle+1, high);
}

results matching ""

    No results matching ""