I’m trying to make a project that asks for the number of strings a person wants, then prompts the person to enter the strings in any order. Then I am supposed to order them alphabetically and I CAN NOT use Java.util at all. I am supposed to use any type of sorting algorithm that can sort the inputted strings in alphabetical order. This is my code so far, could any one help me put a sorting algorithm in my code?
package sorting;
import java.io.*;
public class Sorting
{
private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );
public static void main(String[] arguments) throws IOException
{
System.out.println("How many strings would you like to enter?");
int stringCount = Integer.parseInt(stdin.readLine());
String[] stringInput = new String[stringCount];
String message = "";
for(int i = 0; i < stringCount; i++)
{
System.out.print("Could you enter the strings here: \n");
stringInput[i] = stdin.readLine();
message = message + stringInput[i] + ", ";
}
System.out.println("So you entered:\n" + message);
}
private static void bubbleSort(String[] stringInput, int length) {
int temp, counter, index;
for(counter=0; counter<length-1; counter++) {
for(index=0; index<length-1-counter; index++) {
if(stringInput[index] > stringInput[index+1]) {
temp = stringInput[index];
stringInput[index] = stringInput[index+1];
stringInput[index+1] = temp;
}
}
}
}
}
To point you in a direction think about the following…
Basically the way it works is you have a list lets say in this case of
ints1, 4, 6, 2, 7
and you need to sort it from least to greatest. The way you would do this is like the following using pseudo code:
now this won’t completely sort it on the first try, [in this example that would make your list 1, 4, 2, 6, 7] you would either have to call this function again until the list is fully sorted, or you could look into recursion, or read up about any of the sorts like bubble sort, insertion sort, merge sort, and so on.
It might be usful to mention to make sure you check your Array Bounds because if i+1 is bigger than your list you will get an exception so just keep this in mind.
Good Luck with your Homework and remember, homework isn’t just another thing to add to your grade, but the real importance of homework is to learn and practice or else you will never understand and succeed in whatever class it is. If it is too easy, you probably didn’t learn anything. If it is hard, you probably will learn a lot even if you don’t always get it right.
Happy Coding.