Java字符串冒泡排序 [英] Java String Bubble Sorting
问题描述
我需要使用气泡排序算法按字母顺序对数组进行排序的帮助.
I need help sorting this array in alphabetical order using the bubble sort algorithm.
我的代码是:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
该代码可以编译,但是不会按字母顺序排序.请帮助我.
The code compiles, but it does not sort alphabetical. Please help me.
推荐答案
您的代码中存在三个错误.
You have three errors in your code.
第一个错误是在内部for循环中,在执行check语句的地方,它应该是 i<t1.length-t -1
不是 i<t1.length -1
.您减去t是因为您不想再次遍历整个数组,而只想遍历整个数组的第一部分.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1
not i < t1.length -1
. You subtract t because you do not want to loop through the whole array again, only the first part of it.
第二个和第三个错误在if语句中.您需要将大于符号转换为小于符号,因为您设置compareTo方法的方式将返回负数.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
此行中的另一个错误是,在compareTo参数中放置了 1 +1
,它实际上应该只是 i
,因为您要比对象少一个正在比较.
The other error in this line is that in the compareTo parameter you put 1 + 1
it actually should be just i
, because you want one less than the object it is comparing to.
下面是固定的工作代码(注释是您最初拥有的内容):
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
这篇关于Java字符串冒泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!