js 隨機排序一個數(shù)組,sort中是如何執(zhí)行的?
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){
return Math.random() - 0.5;
})
console.log(arr);
Array.prototype.sort在es規(guī)范中只定義了行為,沒有規(guī)定具體排序算法的實現(xiàn),因此各個引擎的實現(xiàn)有所不同。
對V8而言,數(shù)組長度小于10則使用插入排序,否則使用快速排序
https://github.com/v8/v8/blob...
然后這個方法在已是過去時,4月份V8對array.sort和typedarray.sort進行了重寫,理由是更好的性能。用的是一個叫做torque的語言,貌似是V8自己基于c++開發(fā)的一個DSL
這是array.sort重寫的commit,可以看出實現(xiàn)還是跟原來一樣。性能提升源于C++本身的性能優(yōu)勢。
樓上的大佬解釋了“sort
中是如何執(zhí)行的”,我來回答一下“js隨機排序一個數(shù)組”吧。
題主的方法是錯的,(至少在Chrome中)幾乎所有元素都會留在自己本來的位置!
Results | slot 0 | slot 1 | slot 2 | slot 3 | slot 4 | slot 5 | slot 6 | slot 7 | slot 8 | slot 9 |
---|---|---|---|---|---|---|---|---|---|---|
A's | 2919 | 2889 | 1924 | 1120 | 581 | 296 | 141 | 83 | 34 | 13 |
B's | 2925 | 2859 | 1901 | 1104 | 604 | 294 | 165 | 77 | 48 | 23 |
C's | 1883 | 1951 | 2259 | 1689 | 1030 | 585 | 324 | 165 | 78 | 36 |
D's | 1096 | 1081 | 1742 | 2228 | 1734 | 1005 | 592 | 310 | 144 | 68 |
E's | 550 | 603 | 1059 | 1760 | 2229 | 1785 | 1034 | 564 | 274 | 142 |
F's | 306 | 298 | 558 | 993 | 1738 | 2319 | 1817 | 1064 | 608 | 299 |
G's | 161 | 172 | 295 | 569 | 1056 | 1718 | 2346 | 1915 | 1131 | 637 |
H's | 89 | 80 | 147 | 323 | 575 | 1127 | 1731 | 2595 | 2068 | 1265 |
I's | 45 | 45 | 82 | 146 | 286 | 564 | 1234 | 2015 | 3144 | 2439 |
J's | 26 | 22 | 33 | 68 | 167 | 307 | 616 | 1212 | 2471 | 5078 |
https://jsfiddle.net/rcmp0aLL/
而實際上,題主的方法到底能不能打亂數(shù)組是依賴于sort
的具體實現(xiàn)的。Chrome的具體實現(xiàn)請見樓上大佬,不論如何,結(jié)果是不行的。
正確的姿勢是什么呢?
用lodash的_.shuffle
,簡單,快速,直接,易維護。
或者,實現(xiàn)一個Fisher-Yates算法:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
以上fiddle和代碼取自StackOverflow https://stackoverflow.com/que...
北大青鳥APTECH成立于1999年。依托北京大學(xué)優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國IT技能型緊缺人才,是大數(shù)據(jù)專業(yè)的國家
北大青鳥中博軟件學(xué)院創(chuàng)立于2003年,作為華東區(qū)著名互聯(lián)網(wǎng)學(xué)院和江蘇省首批服務(wù)外包人才培訓(xùn)基地,中博成功培育了近30000名軟件工程師走向高薪崗位,合作企業(yè)超4
中公教育集團創(chuàng)建于1999年,經(jīng)過二十年潛心發(fā)展,已由一家北大畢業(yè)生自主創(chuàng)業(yè)的信息技術(shù)與教育服務(wù)機構(gòu),發(fā)展為教育服務(wù)業(yè)的綜合性企業(yè)集團,成為集合面授教學(xué)培訓(xùn)、網(wǎng)
達內(nèi)教育集團成立于2002年,是一家由留學(xué)海歸創(chuàng)辦的高端職業(yè)教育培訓(xùn)機構(gòu),是中國一站式人才培養(yǎng)平臺、一站式人才輸送平臺。2014年4月3日在美國成功上市,融資1
曾工作于聯(lián)想擔任系統(tǒng)開發(fā)工程師,曾在博彥科技股份有限公司擔任項目經(jīng)理從事移動互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍懿科技有限責任公司從事總經(jīng)理職務(wù)負責iOS教學(xué)及管理工作。
浪潮集團項目經(jīng)理。精通Java與.NET 技術(shù), 熟練的跨平臺面向?qū)ο箝_發(fā)經(jīng)驗,技術(shù)功底深厚。 授課風(fēng)格 授課風(fēng)格清新自然、條理清晰、主次分明、重點難點突出、引人入勝。
精通HTML5和CSS3;Javascript及主流js庫,具有快速界面開發(fā)的能力,對瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁制作和網(wǎng)頁游戲開發(fā)。
具有10 年的Java 企業(yè)應(yīng)用開發(fā)經(jīng)驗。曾經(jīng)歷任德國Software AG 技術(shù)顧問,美國Dachieve 系統(tǒng)架構(gòu)師,美國AngelEngineers Inc. 系統(tǒng)架構(gòu)師。