Home | Projects | Notes > Data Structures & Algorithms > Merge Sort: T = O(n logn) , S = O(n)

Merge Sort: T = O(n logn) , S = O(n)

 

Merge Sort

Algorithm

  1. Input: An array of elements to be sorted.

  2. Divide: Divide the input array into two equal (or nearly equal) halves.

  3. Recursion: Recursively apply merge sort on each of the two halves until each subarray contains only one element or is empty.

  4. Merge: Combine the sorted subarrays by merging them. This involves comparing elements from both subarrays and placing them in order in a new temporary array.

  5. Copy Back: Copy the merged elements from the temporary array back into the original array in their correct sorted order.

  6. Repeat: Continue this process, dividing, sorting, merging, and copying, until the entire array is sorted.

Pseudo-code

 

Code (C++)

 

Code (C)