Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best algorithm to check whether a vector is sorted

What would be the best way to check that a std::vector is sorted? Is there something faster than a loop checking that v[i]<=v[i+1]? Is it faster/cleaner with iterators? Or is it actually better to just call sort every time (though the "v is already sorted" case is quite common)?

We can safely assume the vector only contains PODs, usually floats and sometimes doubles and ints.

The size of the vector is non-trivial (usually a few thousands items) but not extreme (not gigabyte-sized).

  • in some instances we'll sort the vector immediately afterwards, however there are other instances where we don't (it's an error case of our algorithm).
  • we already use a flag "IsSorted" whenever possible.
like image 909
rlerallut Avatar asked Nov 04 '08 14:11

rlerallut


People also ask

How do you know if a vector is sorted?

if (result == false) cout << "Vector elements are not sorted in ascending order." << endl; result = is_sorted(v.

How do you sort a vector using algorithms?

Sorting a vector in C++ Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements.

How do I check if a vector is sorted in R?

unsorted() function in R Language is used to check if an object is sorted or not. It returns False if the object is sorted otherwise True. Here, the output is FALSE for vector because it is sorted and matrix is unsorted, hence the function returns TRUE for matrix.

How do you sort a vector without using sort?

The vector can use the array notation to access the elements. If you don't want to use the default std::sort , or std::sort with custom comparator, you can use qsort or write your own.


2 Answers

Is there something faster than a loop checking that v[i]<=v[i+1] ?

No.

If this is something you wish to check often, you might want to make a wrapper class that keeps a "sorted" flag which starts out False, is set to False whenever an item is added, and add a member function sort() that sets the flag to True after sorting.

like image 173
Deestan Avatar answered Oct 26 '22 21:10

Deestan


The best way is to use std::is_sorted:

is_sorted(v.begin(), v.end())

:-)

like image 28
ShreevatsaR Avatar answered Oct 26 '22 23:10

ShreevatsaR