I am trying to sort two different kinds of arrays. I am sorting Integer arrays in numerical order which I have working and I also need to sort Character arrays in alphabetical order. I am having a little trouble with sorting the Character array. My teacher wants to us to sort capital letters and he wants them to stay capital when printing the array. First I have the Character array convert everything to lower case so it sorts it properly. But how would I get the Character to go back to capital without messing up the order.
import java.util.*;
public class MyProgram extends ConsoleProgram
{
int[] numbers = {4, 2, 3, 1, 11, 9};
Character[] characters = {'z', 'c', 'a', 'q', 'B', 'g'};
public void run()
{
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
Arrays.sort(characters);
for(int i = 0; i < characters.length; i++)
{
if(Character.isUpperCase(characters[i]))
{
characters[i] = Character.toLowerCase(characters[i]);
Arrays.sort(characters);
}
System.out.println(characters[i]);
}
}
}
I convert to an array of strings, sort it ignoring case then convert it back to an array of characters.
public char[] sortArray(char[] arr) {
// Creating a blank string array
String [] end = new String[arr.length];
// Converting (char) arr array to (string) end array.
for(int i = 0; i < arr.length; i++) {
end[i] = "" + arr[i];
}
// Sorts the end array ignoring case
Arrays.sort(end, String.CASE_INSENSITIVE_ORDER);
// Converting (string) end array to (char) arr array.
for(int i = 0; i < arr.length; i++) {
arr[i] = end[i].charAt(0);
}
// Returns arr aray
return arr;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With