jj007
jj007

Reputation: 43

Output Bubble Sort results to an array in java

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;

                     }
             }
      }
}

Upvotes: 0

Views: 581

Answers (2)

Robert Peters
Robert Peters

Reputation: 4104

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;

Upvotes: 1

I82Much
I82Much

Reputation: 27326

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

Upvotes: 0

Related Questions