Merge Sort

About

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 #include <bits/stdc++.h> using namespace std; void print(int a[], int n) { for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; } void merge(int *a, int low, int mid, int high) { int temp[101]; int i, k, j; i = k = low; j = mid + 1; while (i <= mid && j <= high) { if (a[i] < a[j]) { temp[k] = a[i]; k++; i++; } else { temp[k] = a[j]; k++; j++; } } while (i <= mid) { temp[k] = a[i]; i++; k++; } while (j <= high) { temp[k] = a[j]; j++; k++; } for (int x = low; x <= high; x++) { a[x] = temp[x]; } } void mergeSort(int *a, int low, int high) { if (low < high) { int mid = (low + high) / 2; mergeSort(a, low, mid); mergeSort(a, mid + 1, high); merge(a, low, mid, high); } } signed main(){ int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } mergeSort(a, 0, n - 1); print(a, n); return 0; }

Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then it merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.

Pseudocode

  • Declare left variable to 0 and right variable to n-1
  • Find mid by medium formula. mid = (left+right)/2
  • Call merge sort on (left,mid)
  • Call merge sort on (mid+1,rear)
  • Continue till left is less than right
  • Then call merge function to perform merge sort.

Algorithm

  • step 1: start
  • step 2: declare array and left, right, mid variable
  • step 3: perform merge function.
    mergesort(array,left,right)
    mergesort (array, left, right)
    if left > right
    return
    mid= (left+right)/2
    mergesort(array, left, mid)
    mergesort(array, mid+1, right)
    merge(array, left, mid, right)
  • step 4: Stop

Time Complexity

  • Worst Case Time Complexity is: Ω(n log(n))
  • Average Case Time Complexity is: θ(n log(n))
  • Best Case Time Complexity is: Ω(n log(n))