I am new to Java, but to expand my knowledge of it. Below is a class assignment that I'm having a very, very difficult time completing. I need to create a method that passes in a two dimensional string array and then sorts the array by the second element.
Method sortContacts()
- Declared as a public static method, it should take a two-dimensional String array as a parameter, and an integer value for the number of contacts in the array
- Returns nothing o Sorts the contents of the contact list given as a parameter using the lastName as the sorting field
- You may use any of the sorting mechanisms described in the text (bubble, insertion or selection)
- Key concept: as you implement the sort, the trick is to identify the dimension for the values you are comparing and how they relate to the values from your loops.
- Hints:
- Do not rely on the array’s length for your loops, instead use the value from the number of contacts
- Your temp variable will be an
array of size 3,
String[] temp = new String[3]; - You will need to
use the
string1.compareTo(string2)method to compare two strings.
Sample data: (first name, last name, phone number)
String [][] contactsArray = {
{"Emily","Watson","913-555-0001"},
{"Madison","Jacobs","913-555-0002"},
{"Joshua","Cooper","913-555-0003"},
{"Brandon","Alexander","913-555-0004"},
{"Emma","Miller","913-555-0005"},
{"Daniel","Ward","913-555-0006"},
{"Olivia","Davis","913-555-0007"},
{"Isaac","Torres","913-555-0008"},
{"Austin","Morris","913-555-0009"}
public static void sortContact(String[][] contactsArray, int numContacts) {
String[] temp = new String[3];
String [] words = contactsArray[3];
for(int i = 0; i < numContacts-1; i++)
{
int smallest = i;
for(int j = i + 1; j < numContacts-1; j++)
{
//Prints loop variables so I can see them before any action
System.out.println("First: "+words[j]+" " +"Second "+words[i]);
if(words[j].compareTo(words[i]) < 0)
smallest = j;
}
//put the new minimum in the i-th position.
//String temp = words[i];
words[i] = words[smallest];
words[smallest] = temp[i];
}
}
There are tons of examples for integer arrays but not a lot for string arrays,
Any suggestions are appreciated.