mergesort
Merge Sort
- stable sort
- most common implementation does not sort in place
- external merge sort
void mergearray(vector<int> &a, int low, int mid, int high, vector<int> &tmp){ // merge a[low,mid] and a[low+1,high] int i=low, j=mid+1; int k=0; while (i<=mid && j<=high){ if (a[i]<a[j]) tmp[k++]=a[i++]; else tmp[k++]=a[j++]; } while (i<=mid) tmp[k++]=a[i++]; while (j<=high) tmp[k++]=a[j++]; // copy from tmp back to original array for (i=0;i<k;++i) a[low+i] = tmp[i]; } void mergesort(vector<int> &a, int low, int high, vector<int> &tmp){ if (low>=high) return; int mid=(low+high)/2; mergesort(a,low,mid,tmp); mergesort(a,mid+1,high,tmp); mergearray(a,low,mid,high,tmp); } int main() { vector<int> a={1,5,8,3,2}; int n=a.size(); vector<int> tmp(n); mergesort(a,0,n-1,tmp); for (auto x:a) cout<<x<<' '; return 0; }
Time Complexity: O(nlogn)