Noor210111's blog

By Noor210111, 7 months ago, In English

1. sort() function for Array

1.1. Sort in ascending order:

  • sort(arr + desired starting index , arr + desired ending index ); [indexing start from 1]
  • sort(arr (by default index: 1) , arr + desired ending index ); [indexing start from 1]

1.2. Sort in descending order:

  • sort(arr + desired starting index , arr + desired ending index , greater<'int'>()); [indexing start from 1] ['int' without quotation]

2. sort() function for Vector

2.1. Sort in ascending order:

  • sort(vec.begin() + desired starting index , vec.begin() + desired ending index ); [indexing start from 0]
  • sort(vec.begin() (by default index: 0) , vec.end()); [end() for last index]

2.2. Sort in descending order:

  • sort(vec.begin() + desired starting index , vec.begin() + desired ending index + 1, greater<'int'>()); [indexing start from 0] ['int' without quotation]
  • sort(vec.begin() (by default index: 0) , vec.end(), greater<'int'>()); [end() for last index] ['int' without quotation]

2.3. sort() function for Vector Pair:

2.3.1. On the basis of first element:

  • sort(vec.begin(), vec.end()); [Ascending order]
  • sort(vec.begin(), vec.end(), greater<pair<int, int>>()); [Descending order]

    2.3.2. On the basis of second element:

    [Ascending order]
    bool sortbysec(const std::pair<int, int> &a, const std::pair<int, int> &b){return a.second < b.second;}
    sort(vec.begin(), vec.end(), sortbysec);

    [Descending order]
    bool sortbysecdesc(const std::pair<int, int> &a, const std::pair<int, int> &b){return a.second > b.second;}
    sort(vec.begin(), vec.end(), sortbysecdesc);
  • Vote: I like it
  • -19
  • Vote: I do not like it

»
7 months ago, # |
  Vote: I like it 0 Vote: I do not like it

The usage of sort() function is slightly different for array and vector. For example: syntax for starting and ending point, indexing for denoting starting and ending point etc. So in this blog, I have summarized almost all the usage categories of sort() function for array and vector with clarification of the above mentioned difference.