按字母顺序排列字符串(不使用 compareTo 方法) [英] Alphabetize strings (without using compareTo Method)
问题描述
我试图在不使用 compareTo()
的情况下对字符串数组进行排序,但我卡在了 while
循环中.有没有办法在不使用 compareTo()
或 Arrays.sort()
的情况下按字母顺序对字符串进行排序?
I'm trying to sort an array of strings without using compareTo()
, but I am getting stuck on my while
loop. Is there a way to alphabetically sort strings without using compareTo()
or 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--;
}
}
}
}
按字母顺序排列是我的目标,所以我的输出如下
Alphabetization is my goal, so my output would be the following
***********************
hello
java
elephant
array
***********************
***********************
array
elephant
hello
java
***********************
我使用建议的想法添加了这个方法,但我不确定我会放置什么来遍历字符串的索引
I added this method using the idea that was suggested, but I am unsure what I would put in place to run through the index of the string
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()
,所以我会给你关于如何编写自己的方法进行比较的提示.你想要带签名的东西
I'm assuming this is homework, since the obvious way is just to use compareTo()
, so I'll give you a hint on how to write your own method to do the comparison. You want something with signature
int compareStrings(String s, String t);
返回 -1
或 0
或 1
取决于 s
是按字母顺序排列在前面、等于或在字母表中 t
之后.
that returns -1
or 0
or 1
depending on whether s
is alphabetically before, equal to or after t
in the alphabet.
逐个字符遍历两个String
,并且在每个阶段,如果s
中的字符小于t
(这里你可以使用<
)然后返回-1
;如果更大,则返回1
;如果它们相等,请继续.
Go through the two String
s character by character, and at each stage, if the character from s
is less than that of t
(here you can use <
) then return -1
; if it's greater, then return 1
; if they're equal, keep going.
如果 s
中的字符用完了,但 t
中还有一些字符,则返回 -1
,如果是其他方式回合然后返回1
.如果同时用完,返回0
.
If you run out of characters in s
but still have some in t
, then return -1
, and if it's the other way round then return 1
. If you run out of both at the same time, return 0
.
这篇关于按字母顺序排列字符串(不使用 compareTo 方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!