排序字符数组而不使用内置的sort()函数?

huangapple go评论65阅读模式
英文:

Sorting array of chars without using built-in sort()?

问题

以下是您提供的代码的翻译部分:

String input5 = "A2B3C1";
char[] lst5 = input5.toCharArray();

for (int i = 0; i < lst5.length; i++) {
    for (int j = i + 1; j < lst5.length; j++) {
        if ((Character.isDigit(lst5[i]) && Character.isDigit(lst5[j]) && lst5[i] > lst5[j]) || 
            (!Character.isDigit(lst5[i]) && !Character.isDigit(lst5[j]) && lst5[i] > lst5[j]) || 
            (lst5[i] < lst5[j] && (Character.isDigit(lst5[i)))) {
            char tmp = lst5[i];
            lst5[i] = lst5[j];
            lst5[j] = tmp;
        }
    }
}
System.out.println(lst5);

希望这有助于解释您的代码和问题。

英文:

I have the following code:

String input5 = &quot;A2B3C1&quot;;
char[] lst5 = input5.toCharArray();
  
for (int i = 0; i &lt; lst5.length; i++) {
    for (int j = i + 1; j &lt; lst5.length; j++) {
        if ((Character.isDigit(lst5[i]) &amp;&amp; Character.isDigit(lst5[j]) &amp;&amp; lst5[i] &gt; lst5[j]) || 
                (!Character.isDigit(lst5[i]) &amp;&amp; !Character.isDigit(lst5[j]) &amp;&amp; lst5[i] &gt; lst5[j]) || 
                (lst5[i] &lt; lst5[j] &amp;&amp; (Character.isDigit(lst5[i])))) {
            char tmp = lst5[i];
            lst5[i] = lst5[j];
            lst5[j] = tmp;
        }
    }

}
System.out.println(lst5);

What I expected: "ABC123"
But I got: "ABC132"

What did I do wrong?

答案1

得分: 0

Your first for loop should be:

for (int i = 0; i < lst5.length-2; i++)

To more directly answer your question, the expression

(!Character.isDigit(lst5[i]) && !Character.isDigit(lst5[j]) && lst5[i] > lst5[j])

falls through by evaluating to false when both characters are already-sorted digits. The next expression (lst5[i] < lst5[j] && (Character.isDigit(lst5[i)) is treated as though there's certainty that the characters are neither both digits nor both non-digits, which is a fallacy as they could also reach that third expression when already in sorted order.

英文:

Your first for loop should be:

for (int i = 0; i &lt; lst5.length-2; i++)

To more directly answer your question, the expression

(!Character.isDigit(lst5[i]) &amp;&amp; !Character.isDigit(lst5[j]) &amp;&amp; lst5[i] &gt; lst5[j])

falls through by evaluating to false when both characters are already-sorted digits. The next expression (lst5[i] &lt; lst5[j] &amp;&amp; (Character.isDigit(lst5[i])) is treated as though there's certainty that the characters are neither both digits nor both non-digits, which is a fallacy as they could also reach that third expression when already in sorted order.

huangapple
  • 本文由 发表于 2023年2月10日 12:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定