近日,在coderbyte.com上通关娱乐,偶遇sort()
排序大坑。
题目如下:
Have the function AlphabetSoup(str) take the str string parameter being passed and return the string with the letters in alphabetical order (ie. hello becomes ehllo). Assume numbers and punctuation symbols will not be included in the string.
按照习惯答题:
function AlphabetSoup(str) {
// code goes here
if (typeof str !== 'string') return 'not string';
let list = str.split('');
list.sort(function(a, b) { return a > b});
str = list.join('');
return str;
}
通过网站测试,完全正确。但是,当测试字符串长度超过10的时候,问题出现了,
传入字符串onetomewafwrsdxf
,排序结果却是afedfemnoorstwwx
,肉眼可测,结果必然不正确。
做了多次测试同时翻阅多篇资料后,方知:
正常小于10位的InsertionSort
,使用上述方法是没问题的,但是超过10位之后,在QuickSort
中,坑就出现了。
由于在引擎中,数组长度不同,sort()
调用的方法不同,传入的参数判断结果有所不同。
因此建议,直接使用不传参的sort()
,方可保证结果。