# Sorting Operations in header algorithm in C++

The Packet explains the sorting operations defined in the header algorithm with an example of each to have a better understanding.

Sorting operations:

1)is_sorted(): The function checks and returns true if the given sequence is sorted into ascending order else returns false.

Syntax: is_sorted (Iterator pointing to first, iterator pointing to last );

Example:

```#include
#include
using namespace std;
int main()
{
int arr[] = { 5, 8, 9, 2 };
int n1=(sizeof(arr) / sizeof(arr))-1;
int n2=(sizeof(arr) / sizeof(arr));
if (is_sorted(arr, arr + n1))
{
cout << "The given array is sorted in the given range"<<endl;
}
if(!is_sorted(arr,arr+n2))
{
cout << "The given array is not sorted in the given range"<<endl;
}
}
```

2)is_sorted_until(): The function checks and returns the first unsorted element in the given sequence and if the sequence is sorted then returns an iterator pointing to the last.

Syntax: is_sorted_until (Iterator pointing to first, iterator pointing to last );

Example:

```#include
#include
using namespace std;
int main()
{
int arr[] = {5,8,9,2};
int n=(sizeof(arr) / sizeof(arr));
int* x=is_sorted_until(arr, arr + n);
cout<< *x;
}
```

3)sort() :sorts the given sequence into ascending order

Syntax: sort(Iterator pointing to first, iterator pointing to last) //for ascending order

sort(Iterator pointing to first , iterator pointing to last, greater()); //for descending order

Example:

```#include
#include<bits/stdc++.h>
using namespace std;

int main()
{
int arr[] = {5,8,9,2};
int n = sizeof(arr) / sizeof(arr);
sort(arr, arr + n);    // For descending order - sort(arr, arr + n, greater());
cout <<"Sorted array is:"<<endl;
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
```

4) partial_sort(): sorts the first n elements of a range in such a way that half of the sequence is sorted and the other half is unsorted.

Syntax: partial_sort(Iterator pointing to first, iterator pointing to the middle element, iterator pointing to last)

Example:

```#include
#include
#include
using namespace std;
int main()
{
vector arr = {  5,8,5,9,10 };
vector::iterator i;
partial_sort(arr.begin(), arr.begin() + 3, arr.end());
for (i = arr.begin(); i != arr.end(); ++i) {
cout << *i << " ";
}
```

Hope this packet helps you.