Sorting

Sorting in c++

c++ has a sort() function which helps out during contests without taking care of the implementations.

vector<int> v = {4,2,5,3,5,8,3};
sort(v.begin(),v.end());

<aside> 💡

v.begin() and v.end() are referred to as iterators. iterators are just like pointers that point to some elements.

</aside>

After sorting, the contents of the vector will be [2, 3, 3, 4, 5, 5, 8].

The default order is increasing, but a reverse order is possible as follows:

sort(v.rbegin(),v.rend())

// alternate method
sort(v.begin(),v.end(), greater<int>());

sort function for simple arrays

int n = 7; // array size
int a[] = {4,2,5,3,5,8,3};
sort(a,a+n);

sorting a string

string s = "monkey";
sort(s.begin(), s.end());

Sorting a string means that the characters of the string are sorted. For example, the string ”monkey” becomes ”ekmnoy”.