Basic programming - Merge Sort
Approach:
It is a Divide and Conquer problem. Divide the vector into small group to sort, and merge each small groups to the vector.
In the merge() function, we need two new vectors to store those element that is divided into two parts from the vector.
And, INT_MAX
must be added at the end of leftvec
and rightvec
. It's a comparision use. E.g., all of elements in leftvec
are smaller than rightvec
, so do vec[i] = leftvec[left++]
until leftvec[left] = INT_MAX
, and afterwards do vec[i] = rightvec[right++]
. Finally, those elements are sorted.
Space complexity: O(n)
Stable/Unstable: Stable
Source code
Version 1
1 |
|