字符串排序在算法上是如何工作的
How does string sorting work algorithmically?
假设我要编写自己的算法来对字符串数组进行排序。我该怎么做一个算法呢?
我理解使用ascii字符比较字符串中的每个字符的总体思路。
我卡住的部分是比较整个字符串的字母数字。
我想也许我可以得到整个字符串的和,但这不是它的意思。以下是正确的顺序:
aaa
abccccccccccccccccc
ac
而不是这个关于sum:
aaa
ac
abcccccccccccccccc
l.sort(function (a,b) {
let min = Math.min(a.length, b.length);
for (let i = 0; i < min; i++) {
let l = a[i];
let r = b[i];
if (l !== r) {
return l.charCodeAt(0) - r.charCodeAt(0);
}
}
return a.length - b.length;
});
查看Java.Util.String
方法compareTo
的实现将帮助您了解如何在lexicographical order
中比较两个String
。
/**
* Compares two strings lexicographically.
* The comparison is based on the Unicode value of each character in
* the strings. The character sequence represented by this
* {@code String} object is compared lexicographically to the
* character sequence represented by the argument string. The result is
* a negative integer if this {@code String} object
* lexicographically precedes the argument string. The result is a
* positive integer if this {@code String} object lexicographically
* follows the argument string. The result is zero if the strings
* are equal;
*/
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- 最大高度转换不;不工作,工作缓慢
- Gulp-rev:不是第一次工作,而是在第一次工作之后工作
- 在JavaScript中的类中,push和concat的工作方式有何不同
- JQuery - Ajax: encodeUriComponent不工作(EncodeUri工作)