英文:
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 = "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);
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 < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论