我有个问题需要我整理一下姓氏。我正在使用冒泡排序,但在分割名字和姓氏时遇到问题。在使用冒泡排序方法之前我就遇到过这种情况。
public class Surnames
{
public static void main(String args[])
{
String names[] = {"Dippy Duck", "Annie Apple" etc}
char[] charnames = names.toCharArray();
bubblesort(charnames);
String sortedString = new String(charnames);
System.out.println(sortedString);
public static void bubblesort(char[] charnames)
{
int limit = charnames.length;
for(int i =0; i < limit -1; i++)
{
for(int j =0; j < limit -i - 1; j++)
{
if(charnames[j] > charnames[ j+1])
{
char temp = charnames[j];
charnames[j] = charnames[j+1]
charnames[j+1] = temp;
}
}
}
}
我试图让它像安妮·苹果一样打印出来,然后按字母顺序对它们进行排序,但我不知道。
我清理了代码。
Type x[]
是旧的C/C++兼容样式,最好将类型保持在一起:Type[] x
。limit
的数组边界似乎有点错误。我冒昧地用了另一个名字(n
)。第二个 j 循环是可行的,但你会发现以下更简单:
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
...
private static final Logger LOGGER = Logger.getLogger(Surnames.class.getName());
public static void main(String[] args) {
String[] names = {"Dippy Duck", "Annie Apple"};
for (String name: names) {
char[] nameChars = name.toCharArray();
bubblesort(nameChars);
String sortedName = new String(nameChars);
System.out.printf("%s -> %s%n", name, sortedName);
}
}
与
public static void bubblesort(char[] chars) {
LOGGER.log(Level.TRACE, "bubblesort: {0}", chars);
int n = chars.length;
boolean swapped;
do {
swapped = false
for (int i = 0; i < n - 1; ++i) { // i and i+1 valid indices.
if (chars[i] > chars[i + 1]) {
char temp = chars[i];
chars[i] = chars[i + 1];
chars[i + 1] = temp;
swapped = true;
LOGGER.log(Level.TRACE, "swapped: [{0}] {1}", i, chars);
}
}
--n;
} while (swapped);
LOGGER.log(Level.TRACE, "result: {0}", chars);
}
使用记录器有助于运行检查。