字符串排序在算法上是如何工作的

How does string sorting work algorithmically?

本文关键字:工作 何工作 排序 算法 字符串      更新时间:2023-09-26

假设我要编写自己的算法来对字符串数组进行排序。我该怎么做一个算法呢?

我理解使用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;
}