2012-01-28 36 views
0

您好我有一个冒泡排序方法,它接受我的字符串数组并对它们进行排序。不过,我希望排序的字符串被输入到另一个数组中,以便原始未排序的数组可以用于其他事情。任何人都可以帮助我或引导我朝着正确的方向发展吗?由于输出气泡排序结果到java中的数组

新的数组,其中我想用来存储串被称为myArray2 我的继承人冒泡排序的代码

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; 

        } 
      } 
     } 
} 
+0

为什么不使用'System.arraycopy()'并排序该数组。 – RanRag 2012-01-28 22:42:11

回答

0

让你的方法返回一个String [],而不是无效的。

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; 
} 
+0

我试过,但原始数组仍然得到排序 – jj007 2012-01-28 22:55:03

+0

对不起,它确实工作,但我不能让它打印在我的JList对象被称为打印。我尝试调用一个新的JList打印(副本),但它并没有工作 – jj007 2012-01-28 23:09:46

+0

@ jj007:它适用于'JList'.Here是我尝试的方式'String [] temp = t.sortStringBubble(x);'比'JList list =新的JList(temp)'。这里't'是'sortStringBubble'所在类的对象。 – RanRag 2012-01-28 23:24:05

1

不确定 1)改变方法签名是字符串[]

public static String[] sortStringBubble(String[] input ) { 

2)添加一个新的字符串[]×

String[] x = (String[])input.clone(); 

3)添加一个返回X在底部

return x; 
+0

我试过了,但原始数组仍然得到排序 – jj007 2012-01-28 22:53:46

+0

对不起,但它无法正常工作,但我不能让它打印在我称为print的JList对象中。我试图调用一个新的JList打印(x),但它没有工作 – jj007 2012-01-28 23:10:05

+1

Nver介意我修复它,感谢您的帮助 – jj007 2012-01-28 23:29:00