当前位置:网站首页>Detailed explanation of sorting sort method of JS array
Detailed explanation of sorting sort method of JS array
2022-06-30 04:56:00 【Front end students】
analysis
Array.prototype.sort()
sort() Method to sort the elements of an array , And returns an array .
If omitted ,sort Method will call toString() Method , And then according to unicode Code to sort , If the array contains undefined Elements , They will be tailed .
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
var arr=[3,24,6,18,7,21];
arr.sort();
console.log(arr); //=>[18,21,24,3,6,7]
Array element exceeds 2 There's something wrong with the number order , That's already been said sort Sort by element unicode Code to sort , First, the first place of each item should be followed ascii Sort from small to large , If the first digit is the same, the second digit will be followed unicode Sort from small to large . because 1、2、3、6、7 Of unicode The codes are :31、32、33、36、37, So the order first is :[18,14,3,6,7,21] First of all ascii Same code , So compare the second place ,4 Of ascii Code is 34, therefore 21 stay 24 In front of , The final sorting result is :[18,21,24,3,6,7]. Although the reason is found , But it is not the sort result we want ,Array.sort() Method allows us to pass in a comparison function .
Sort
Ascending order : return a - b
null : return a - b
sort Source code analysis
Look up v8 Source code sort part We can find out , For the number of elements to be sorted n, There are several cases of specific sorting strategies :
When n<=10 when , Use insert sort ;
When n>10 when , Use three-way quick sort ;
10<n <=1000, Use the median as the sentinel element ;
n>1000, every other 200~215 Pick out one element , Put it in a new array , And then sort it out , Find the number in the middle , As a median .
At first glance, you may have two problems
1、 Why do I use fast sorting when there are fewer elements
In fact, it is not difficult to find out the reason after careful analysis . For interleaved and quick rows , The theoretical average time complexity is O(n^2) and O(nlogn), In the best case, the time complexity of the interpolation is O(n). It is not difficult to draw a conclusion by comparison , When n When I was young enough , Fast platoon advantage becomes smaller . In fact, the sorting performance of optimized interpolation for small data sets can exceed that of fast interpolation .
2、 Why choose the sentinel element
Because the performance bottleneck of quick sort is the depth of recursion , The worst case scenario is that every sentinel is a minimum or maximum element , So for partition( On one side are elements smaller than sentinels , On the other side are elements larger than sentinels ) when , One side will be empty . If you go on like this , The number of levels of recursion is n, And the complexity of each layer is O(n), So fast platoon will degenerate into O(n^2) Level .
This situation should be avoided as much as possible , So how to avoid ? Is to keep the sentinel element in the middle of the array as much as possible , Make the maximum or minimum possible
Finally, let's take a look at the sort Basic structure
function ArraySort(comparefn) {
CHECK_OBJECT_COERCIBLE(this,"Array.prototype.sort");
var array = TO_OBJECT(this);
var length = TO_LENGTH(array.length);
return InnerArraySort(array, length, comparefn);
}
function InnerArraySort(array, length, comparefn) {
// The comparison function did not pass in
if (!IS_CALLABLE(comparefn)) {
comparefn = function (x, y) {
if (x === y) return 0;
if (%_IsSmi(x) && %_IsSmi(y)) {
return %SmiLexicographicCompare(x, y);
}
x = TO_STRING(x);
y = TO_STRING(y);
if (x == y) return 0;
else return x < y ? -1 : 1;
};
}
function InsertionSort(a, from, to) {
// Insertion sort
for (var i = from + 1; i < to; i++) {
var element = a[i];
for (var j = i - 1; j >= from; j--) {
var tmp = a[j];
var order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
}
function GetThirdIndex(a, from, to) { // The number of elements is greater than 1000 When looking for sentinel elements
var t_array = new InternalArray();
var increment = 200 + ((to - from) & 15);
var j = 0;
from += 1;
to -= 1;
for (var i = from; i < to; i += increment) {
t_array[j] = [i, a[i]];
j++;
}
t_array.sort(function(a, b) {
return comparefn(a[1], b[1]);
});
var third_index = t_array[t_array.length >> 1][0];
return third_index;
}
function QuickSort(a, from, to) { // Fast sort implementation
// Sentry position
var third_index = 0;
while (true) {
if (to - from <= 10) {
InsertionSort(a, from, to); // Small amount of data , Use insert sort , Faster
return;
}
if (to - from > 1000) {
third_index = GetThirdIndex(a, from, to);
} else {
// Less than 1000 Take the midpoint directly
third_index = from + ((to - from) >> 1);
}
// Let's start the quick platoon
var v0 = a[from];
var v1 = a[to - 1];
var v2 = a[third_index];
var c01 = comparefn(v0, v1);
if (c01 > 0) {
var tmp = v0;
v0 = v1;
v1 = tmp;
}
var c02 = comparefn(v0, v2);
if (c02 >= 0) {
var tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
var c12 = comparefn(v1, v2);
if (c12 > 0) {
var tmp = v1;
v1 = v2;
v2 = tmp;
}
}
a[from] = v0;
a[to - 1] = v2;
var pivot = v1;
var low_end = from + 1;
var high_start = to - 1;
a[third_index] = a[low_end];
a[low_end] = pivot;
partition: for (var i = low_end + 1; i < high_start; i++) {
var element = a[i];
var order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start == i) break partition;
var top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
// The core idea of fast platoon , Call the quick sort method recursively
if (to - high_start < low_end - from) {
QuickSort(a, high_start, to);
to = low_end;
} else {
QuickSort(a, from, low_end);
from = high_start;
}
}
}
边栏推荐
- Redis implements SMS login function (I) traditional session login
- 力扣2049:统计最高分的节点数目
- Why does the computer have no network after win10 is turned on?
- SSL universal domain name certificate
- SCM learning notes: interrupt learning
- 力扣27. 移除元素
- Detailed explanation of the process of "flyingbird" small game (camera adjustment and following part)
- Spring Festival Tourism Strategy: welcome the new year in Bangkok, Thailand
- A must see cruise experience in Bangkok: visit the Mekong River and enjoy the scenery on both sides of the river
- What is multimodal interaction?
猜你喜欢

Sectigo certificate

力扣977. 有序数组的平方

Geotrustov wildcard

Create a simple battle game with photon pun

PS1 Contemporary Art Center, Museum of modern art, New York

Exploration of unity webgl

【Paper】2021_ Observer-Based Controllers for Incrementally Quadratic Nonlinear Systems With Disturbanc
![[UAV] gyroscope data analysis, taking Victor intelligent jy901b as an example](/img/d7/7bf43437edb87b69cdc5ae858f44e1.jpg)
[UAV] gyroscope data analysis, taking Victor intelligent jy901b as an example

Output directory of log files after unity3d packaging

Unity3d lookat parameter description
随机推荐
Connect to the database and run node JS running database shows that the database is missing
0 foundation starts self-study unit notes control direction becomes larger
【Paper】2015_ Coordinated cruise control for high-speed train movements based on a multi-agent model
Oculus quest2 development: (I) basic environment construction and guide package
redis集群概念
Unit screenshot saved on the phone
One interview question every day to talk about the process of TCP connection and disconnection
SCM learning notes: interrupt learning
Introduction to some representations, neighbors and degrees of Graphs
Detailed explanation of the process of "flyingbird" small game (camera adjustment and following part)
力扣59. 螺旋矩阵 II
Force buckle 349 Intersection of two arrays
Deeply understand the function calling process of C language
Modbus protocol register
Singapore must visit these scenic spots during the Spring Festival
Four methods of unity ugui button binding events
Preorder traversal of Li Kou 589:n fork tree
Create transfer generation point
Moore Manor diary I: realize the reclamation, sowing, watering and harvest in Moore Manor
Passing values between classes using delegates and events