为什么我的排序循环似乎附加了一个不应该添加的元素? [英] Why does my sorting loop seem to append an element where it shouldn't?

查看:21
本文介绍了为什么我的排序循环似乎附加了一个不应该添加的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 compareTo() 对字符串数组进行排序.这是我的代码:

I am trying to sort an array of Strings using compareTo(). This is my code:

static String Array[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
String temp;

public static void main(String[] args)
{

   for (int j=0; j<Array.length;j++)
   {
       for (int i=j+1 ; i<Array.length; i++)
       {
           if (Array[i].compareTo(Array[j])<0)
           {
               String temp = Array[j];
               Array[j] = Array[i];
               Array[i] = temp;
           }
       }
       System.out.print(Array[j]);
   }
}

现在输出是:

Hello  This Example Sorting is

我得到了结果,但不是我想要得到的结果,它们是:

I am getting results, but not the results I want to get, which are:

Hello This Example Is Sorting

如何调整我的代码以正确对字符串数组进行排序?

How can I adjust my code to sort the string array properly?

推荐答案

您的输出是正确的.表示开头的Hello"和This"的白字.

Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.

另一个问题是您的方法论.使用 Arrays.sort() 方法:

Another issue is with your methodology. Use the Arrays.sort() method:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);

输出:

 Hello
 This
Example
Is
Sorting

这里数组is"的第三个元素应该是Is",否则排序后会排在最后.因为 sort 方法内部使用 ASCII 值对元素进行排序.

Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.

这篇关于为什么我的排序循环似乎附加了一个不应该添加的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆