Hi I have a bubble sort method that takes my array of strings and sorts them. However I want the sorted strings to be entered into another array so that the original unsorted array can be used for other things. Can anyone help me or guide me in the right direction? Thanks
The new array where I would like to store the strings is called myArray2 Heres my bubble sort code
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;
}
}
}
}
Sure 1) Change the method signature to be String[]
public static String[] sortStringBubble( String[] input ) {
2) add a new String[] x
String[] x = (String[])input.clone();
3) add a return x at the bottom
return x;
Make your method return a String[] rather than 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.