As far as I can tell, inplace_merge does the exact same thing as sort, except it only works in certain circumstances (When the container is already in two sorted parts).
In other words, is there an difference between these two:
int first[] = {1,3,5,7};
int second[] = {2,4,6,8};
vector<int> v(8);
vector<int>::iterator it;
copy(first,first+4, v.begin());
copy(second,second+4, v.begin()+4);
inplace_merge(v.begin(), v.begin()+4, v.end())
.
int first[] = {1,3,5,7};
int second[] = {2,4,6,8};
vector<int> v(8);
vector<int>::iterator it;
copy(first,first+4, v.begin());
copy(second,second+4, v.begin()+4);
sort(v.begin(), v.end())
Is the only difference going to be efficiency?
Their complexity is not the same:
sort() has a worst case of
O(N²), depending on the sorting algorithm used by your STL implementation.inplace_merge() has a worst case of
O(N*log(N))and a best case ofO(N-1), so it will never be slower thansort()(with the same inputs).Also, as others have pointed out,
inplace_merge()is stable: it preserves the ordering of items whose sort key is the same.sort()does not guarantee this. stable_sort() does, and its worst-case complexity isO(N*log(N)²).