I need to sort my array in alphabetical order. The program inputs N words(strings) and outputs them in alphabetical order. I have started out by using specific words to make sure everything is working correctly. I need to change this to accept any input. Any help would be appreciated!

public class Names
{
     public static void main(String[ ] args)
     {
       String[ ] names = {"joe", "slim", "ed", "george"};
             sortStringBubble (names);
             for ( int k = 0;  k < 4;  k++ )
                System.out.println( names [ k ] );
      }

      public static void sortStringBubble( String  x [ ] )
      {
            int j;
            boolean flag = true;  // determine if sort is finished
            String temp;

            while ( flag )
            {
                  flag = false;
                  for ( j = 0;  j < x.length - 1;  j++ )
                  {
                          if ( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 )
                          {     // ascending sort
                                      temp = x [ j ];
                                      x [ j ] = x [ j+1];  // swapping
                                      x [ j+1] = temp; 
                                      flag = true;
                           } 
                   } 
            } 
      } 
}

Recommended Answers

All 10 Replies

I need to change this to accept any input.

What are the possible sources for input?
Files, internet connection, GUI text boxes, console input?

If its console input, look at the Scanner class. There are many code samples on this forum for you to look at. Use the Search.

You could try this:

String[] names = {"joe", "slim", "ed", "george"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));

Sorry, meanwhile you have changed your posting.

-- tesu

I have fixed my code to use Scanner but I have an error on my these two because I changed names to a string and not an array. How do I fix these?

sortStringBubble (names);
	for ( int k = 0;  k < 4;  k++ )
		System.out.println( names[k] );

Make sense?

Here is my whole code

import java.util.Scanner;
public class Names
{
public static void main(String[ ] args)
{
	Scanner scanner = new Scanner (System.in);
	String names;
	System.out.print("Enter names you would like sorted alphabetically: ");
	names = scanner.next();
	sortStringBubble (names);
	for ( int k = 0;  k < 4;  k++ )
		System.out.println( names[k] );
}
public static void sortStringBubble( String  x [ ] )
{
	int j;
	boolean flag = true; //determine if sort is finished
	String temp;
	while ( flag )
{
		flag = false;
		for ( j = 0;  j < x.length - 1;  j++ )
{
			if( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 )
			{       // ascending sort
				temp = x [ j ];
				x [ j ] = x [ j+1];  // swapping
				x [ j+1] = temp;
				flag = true;
				}
			}
		}
	}
}

I have an error

What is the error?
Please copy and paste the full text of the message here.

You need an array of String to read into before sorting. You should use a loop to read in Strings from the user and save them in the array. When the user says there is no more input, then exit the loop and do the sort. How to do this will require some design thoughts.

This is what it says for my errors:

Line 10: method sortStringBubble(String[])in the Names is not applicable for the argument (string)

and

Line 12: The type of the expression must be an array type but it resolved to String

Line 10: method sortStringBubble(String[])in the Names is not applicable for the argument (string)

The method is defined to take a String array as its arg. You have given it a String.

Line 12: System.out.println( names[k] );

Here names is a String but you have coded it as an array: names[k]

See my previous post about what you need to do.

One error: In line 7 you define name as String instead of String array.
Suggestion:
(1) Should we just use the argument of the main method so that the body of the main method will be:

sortStringBubble (args);
	for ( String s: args )
		System.out.print( s + " " );
		System.out.println();

(2) To enhance the efficiency of the bobble sort one may add an outer loop ( for (int i =0; i<x.length-1 ;i++){...} ) so that one may not check the stable region.

while ( flag )
   {
	flag = false;
	for (int i =0; i < x.length -1;  i++)
	for ( j = i;  j < x.length - 1;  j++ )
         {
	if( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 )
	{       // ascending sort
		temp = x [ j ];
		x [ j ] = x [ j+1];  // swapping
		x [ j+1] = temp;
		flag = true;
		}
	}
}

The above code for suggestion (2) is not properly made.
There is a modified bobble sort for your reference.

stable region

public static void sortStringBubble( String  x [ ] ) {
	int i, j, n = x.length;
	boolean flag=false; //determine if sort is finished. 
	String temp;
	
	/* Notes  
	 * after each outer loop one has to check if the flag is true. flag is true, implying that every elements are already in the order.
	 * If so, the outer "for loop" terminates immediately because every elements are already in order.*/	
	
	for (i=0; (i <n-1) && !flag; i++) {
	   flag = true; // before starting the next scanning make flag true, assuming that every elements are in the order
	for ( j = 0; j < n-1-i; j++ )// n-1-i implying the looping upper range becomes smaller and smaller because no need to check the "stable region" 	
            if( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 ){       // ascending sort
		temp = x [ j ];
		x [ j ] = x [ j+1];  // swapping
		x [ j+1] = temp;
		flag = false;  // Since there is a swapping the flag becomes false. This means further scanning/looping is needed.
		}
// if no swapping happened, implying that every elements are in order and further scanning (looping) is not needed.			
		}
  	}

Tell me more about n-1-i. I have never seen this please.

In bubble sort, sorting on the stable region is unnecessary.
As previous post (28 days ago) points out:
after first run of the outerloop, the maximum of the array will be located on the left end (the left most).
after the second run of the outerloop, the next to the maximum will be placed on the second left location.
.....
In this way, these miximum, next to maximum, next ot next to maximum, and so on ... , have become placed in their correct locations in terms of order. They are sorted. Such a partially sorted region is called stable region, as indicated by the red color in a previous post. No more sorting on this region is needed. The "n-i-i" is the upper(left) limit of the scanning(sorting) by the nested loop. Since 'i' increases the upper(left) limit decreases so that the red region wouldn't be re-sorted. Therefore, we have saved the unnecessary sorting on the stable region.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.