# Sorting

## Sorting

Default ways to sort in C++:&#x20;

`sort(v.begin(), v.end());` on vectors

`sort(arr, arr + n);`on arrays

**By default, the sort() function sorts the elements in ascending order.**

**To sort in descending order:**

`sort(arr, arr + n, greater<int>());`

The time complexity of most sorting is O(NlogN)

## Custom Comparator

One often needs to apply certain types of sorting that are not provided by default by C++.&#x20;

This would apply to using other C++ STLs such as set, map, priority\_queue, etc, as well as custom classes.

```cpp
bool cmp(const Edge &x, const Edge &y) { return x.w < y.w; }
sort(begin(v), end(v), cmp);
```

Or written in lambda expression:

```cpp
sort(begin(v), end(v), [](const Edge &x, const Edge &y) { return x.w < y.w; });
```

Comparators usually compare two objects in the following way, in ascending order:

* If object $$xxx$$ is less than object $$yyy$$, return `true`
* If object $$xxx$$ is greater than **or equal** to object $$yyy$$, return `false`

## Typical Data Structures

```cpp
set<int, greater<int>> a;
map<int, string, greater<int>> b;
priority_queue<int, vector<int>, greater<int>> c;
```

Note: Priority queue by default is a max heap.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://welchj.gitbook.io/cp-notes/language-specifics/sorting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
