在java中将气泡排序结果输出到数组
嗨,我有一个冒泡排序方法,它接受我的字符串数组并对它们进行排序。但是,我希望将已排序的字符串输入到另一个数组中,以便原始未排序的数组可以用于其他事情。有人能帮我或指引我正确的方向吗?谢谢 我想存储字符串的新数组称为myArray2 这是我的气泡排序代码在java中将气泡排序结果输出到数组,java,arrays,sorting,arraylist,bubble-sort,Java,Arrays,Sorting,Arraylist,Bubble Sort,嗨,我有一个冒泡排序方法,它接受我的字符串数组并对它们进行排序。但是,我希望将已排序的字符串输入到另一个数组中,以便原始未排序的数组可以用于其他事情。有人能帮我或指引我正确的方向吗?谢谢 我想存储字符串的新数组称为myArray2 这是我的气泡排序代码 public static void sortStringBubble( String x [ ] ) { int j; boolean flag = true; String temp;
public static void sortStringBubble( String x [ ] )
{
int j;
boolean flag = true;
String temp;
while ( flag )
{
flag = false;
for ( j = 0; j < x.length - 1; j++ )
{
if ( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 )
{
temp = x [ j ];
x [ j ] = x [ j+1];
x [ j+1] = temp;
flag = true;
}
}
}
}
publicstaticvoid排序字符串ubble(字符串x[]
{
int j;
布尔标志=真;
字符串温度;
while(旗帜)
{
flag=false;
对于(j=0;j0)
{
温度=x[j];
x[j]=x[j+1];
x[j+1]=温度;
flag=true;
}
}
}
}
使方法返回字符串[],而不是void
public static String[] sortStringBubble( String x [ ] )
String[] copy = new String[x.length];
System.arraycopy(x, 0, copy, 0, x.length);
// do everything on the copy
return copy;
}
当然
1) 将方法签名更改为String[]
public static String[] sortStringBubble( String[] input ) {
2) 添加新字符串[]x
String[] x = (String[])input.clone();
3) 在底部添加一个返回x
return x;
为什么不使用
System.arraycopy()
,然后对该数组进行排序。很抱歉,它确实有效,但我无法在我的JList对象(称为print)中打印它。我试着调用一个新的JList print(copy),但没有成功work@jj007:它可以与JList
配合使用。以下是我尝试的方法String[]temp=t.sortstringubble(x)代码>大于JList列表=新JList(temp)
。这里的t
是sortstringubble
所在的类的对象。很抱歉,它确实有效,但我无法在我的JList对象(称为print)中打印它。我试着调用一个新的JList print(x),但它不起作用