JavaScript中sort()函數的排序邏輯

在JavaScript中sort()函數默認會把數組的元素轉換成字符串,然後再進行排序。如果,數組中的元素是 number 類型的,那麼得到結果可能和我們想的不一樣。
舉例如下:

arr = [50, 90, 1, 10, 2];
// 比如 arr 數組直接使用 sort() 方法進行排序時,會把該數組中的每個元素都轉化成字符串,然後再進行排序得到的結果爲:[1, 10, 2, 50, 90]
// 我們期望的結果是:[1, 2, 10, 50, 90];

那麼,怎麼樣才能讓數組 arr 使用 sort() 方法後得到想要的結果呢?在使用 sort() 方法對 arr 數組進行排序時需要傳入一個函數作爲其參數。具體示例如下所示[1]

// 需要排序的數組
var arr = [50, 90, 1, 10, 2];

// 按照升序對arr中的元素進行排列的方法
arr = arr.sort((current, next) => {
	// 即按升序排序
	return current - next;
});

// 上述代碼使用sort()方法進行排序的實際思路如下所示:
// 1. current = 50, next = 90
//    current - next = 50 - 90 = -40
//    由於 (current - next) 的結果爲負數,因此無需變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [50, 90, 1, 10, 2];

// 2. current = 90, next = 1
//    current - next = 90 - 1 = 89
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [50, 1, 90, 10, 2];

// 3. 此時,sort()會判斷,arr 數組中 90 前面的兩個元素是否進行過比較。如果沒有進行過比較,則需要進行比較處理。即:
//    此時,需要比較的數組元素爲 50 和 1,即
//    current = 50, next = 1
//    current - next = 50 - 1 = 49
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 50, 90, 10, 2];

// 4. sort()能夠識別數組中的兩個元素是否已經進行過比較,如果已經進行過比較那麼不會重複再比較一次。此時,current 和 next 的值如下所示:
//    current = 90, next = 10
//    current - next = 90 - 10 = 80
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 50, 10, 90, 2];

// 5. current = 50, next = 10
//    current - next = 50 - 10 = 40
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 10, 50, 90, 2];

// 6. current = 1, next = 10
//    current - next = 1 - 10 = -9
//    由於 (current - next) 的結果爲負數,因此無需改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 10, 50, 90, 2];

// 7. current = 90, next = 2
//    current - next = 90 - 2 = 89
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 10, 50, 2, 90];

// 8. current = 50, next = 2
//    current - next = 50 - 2 = 48
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 10, 2, 50, 90];

// 9. current = 10, next = 2
//    current - next = 10 - 2 = 8
//    由於 (current - next) 的結果爲正數,因此需要改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 2, 10, 50, 90];

// 10. current = 1, next = 2
//    current - next = 1 - 2 = -1
//    由於 (current - next) 的結果爲負數,因此無需改變數組元素的索引位置,此時經過排序後的數組如下所示:
//    [1, 2, 10, 50, 90];
// 自此,使用sort()函數對數組中元素爲number類型的數組完成了升序排序。如果要進行降序排列,那麼,只需要把 current - next 修改 next - current 即可。

參考文章:

[1] https://stackoverflow.com/questions/3423394/algorithm-of-javascript-sort-function
[2]JavaScript的sort()方法的底層實現:https://github.com/v8/v8/blob/ad82a40509c5b5b4680d4299c8f08d6c6d31af3c/src/js/array.js的第710行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章