Java字符串冒泡排序

时间:2013-10-06 21:56:31

标签: java sorting bubble-sort

我需要帮助使用冒泡排序算法按字母顺序对此数组进行排序。

我的代码是:

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]);
        }
    }
}

代码编译,但不按字母顺序排序。请帮帮我。

2 个答案:

答案 0 :(得分:2)

您的代码中有三个错误。

第一个错误发生在内部for循环中,在你执行check语句的地方,它应该是i < t1.length - t -1而不是i < t1.length -1。你减去t因为你不想再遍历整个数组,只是它的第一部分。

第二个和第三个错误在if语句中。您需要将大于符号转换为小于符号,因为您设置compareTo方法的方式,它将返回一个负数。

此行中的另一个错误是,在compareTo参数中,您放置1 + 1它实际上应该只是i,因为您想要比它所比较的​​对象少一个。

下面是固定的工作代码(评论是你原来的):

   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]);
        }
   }

答案 1 :(得分:0)

请更改

String[] t1 = s1.split(", "); 

String[] t1 = s1.split("");

这将解决问题。

相关问题