Which algorithm does the JavaScript Array#sort() function use?

JavascriptObject Oriented ProgrammingFront End Technology

Javascript specification doesn't specify a particular algorithm to be used in the Array.sort implementation. This is left on the implementor to decide. So different JS engines use different sorting algorithms.

Mozilla(Spider Monkey JS engine) uses mergeSort. You can see the code written for it in C in the Mozilla repository: https://dxr.mozilla.org/seamonkey/source/js/src/jsarray.c

WebKit(Chrome, Safari, etc) do not directly use a sorting algorithm, instead they choose the algorithm based on element types and length of the array. For example,

Numeric arrays use C++ Std library's quick sort function.

Non-numeric arrays use merge sort.

In some other cases it uses selection sort.

It depends on the datatype and size of array elements which algorithm will be used to sort the array.

Published on 16-Sep-2019 10:58:03