# JavaScript Built-in sort() method

## **How does JS built-in sort() method work?**
- The sort method will always sort arrays in place. The items are first converted to strings, and then their sequences of UTF-16 code units values are compared to determine the default sort order, which is **ascending**.

## **Example: **

![code.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1669200695208/WetGuNrAu.png align="left")

The problem of the sorting is that it only works well with strings. But for sorting numbers, it becomes a disaster. For example:  if numbers are sorted as strings, then "25" is bigger than "100". Because "2" is bigger than "1".

## **Example: **

![code.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1669200955849/ZxIvs2_tL.png align="left")

We can fix this issue if we provide a compare function in the sort function.

## **The Compare Function: **
The purpose of the compare function is to define an alternative sort order.

```
function(a, b){return a - b}
```

When sort() function compares two values, it sends the values to the compare function, and sorts the value according to the returned (negative, zero, positive) value.

- If the result is negative, **a** is sorted before **b**.
- If the result is positive, **b** is sorted before **a**.
- If the result is 0, no changes are done with the sort order of the two values.

## **Sort function with compare function: **

![code.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1669203031920/u9k4qxFXQ.png align="left")

We can also use the same trick to sort an array in descending order:

![code.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1669204545932/2envimftb.png align="left")

## **Time Complexity: **
1. **Average Case: **O(nlog(n))
2. **Worst Case: ** O(n<sup>2</sup>)

## **Space Complexity: **
- It does not require any additional storage. Thus, the space complexity is O(1).

## **Conclusion: **
In this article, we talked about the javascript built-in **sort()** function and its issues. Additionally, we discussed how to solve the sorting issue using the **compare function**.

