我尝试在不使用 compareTo()
的情况下对字符串数组进行排序,但我陷入了 while
循环中。有没有一种方法可以在不使用 compareTo()
或 Arrays.sort()
的情况下按字母顺序对字符串进行排序?
public class mycode
{
public static void main(String[ ] args)
{
String[ ] ar = {"hello", "java", "elephant", "array"};
mycode.display(ar);
mycode.bubbleSort(ar);
mycode.display(ar);
}
static void display(String[] ar)
{
System.out.println("***********************");
for(int i = 0; i < ar.length; i++)
{
System.out.println(ar[i]);
}
System.out.println("***********************");
}
static void bubbleSort(String[] ar)
{
int theFollower;
for(int currStart = 1; currStart < ar.length; currStart++)
{
theFollower = currStart;
while(theFollower != 0 && ar[theFollower] < ar[theFollower - 1]) //this is where my problem is
{
String swap = ar[theFollower];
ar[theFollower] = ar[theFollower - 1];
ar[theFollower - 1] = swap;
theFollower--;
}
}
}
}
按字母顺序排列是我的目标,所以我的输出如下
***********************
hello
java
elephant
array
***********************
***********************
array
elephant
hello
java
***********************
我使用建议的想法添加了这个方法,但我不确定我会放置什么来运行字符串的索引
int alphabetize(String a, String b)
{
String A = a.toLowerCase();
String B = b.toLowerCase();
if (A < B)
{
return -1;
}
else if (A > B)
{
return 1;
}
else
{
}
}
最佳答案
我假设这是作业,因为显而易见的方法就是使用 compareTo()
,所以我将提示您如何编写自己的方法来进行比较。您想要带有签名的东西
int compareStrings(String s, String t);
返回 -1
或0
或1
取决于是否s
按字母顺序位于 t
之前、等于或之后在字母表中。
浏览两个String
s 逐个字符,并且在每个阶段,如果字符来自 s
小于 t
(这里你可以使用 <
)然后返回 -1
;如果更大,则返回 1
;如果它们相等,则继续。
如果 s
中的字符用完但仍然有一些在 t
,然后返回-1
,如果是相反则返回 1
。如果同时用完两者,请返回 0
.
关于java - 按字母顺序排列字符串(不使用compareTo方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789205/