Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Sorting with Integers and Characters

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]);
    }
  }
}
like image 410
Benjamin Kamide Avatar asked Jan 30 '26 23:01

Benjamin Kamide


1 Answers

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;
}
like image 57
Tobias Steely Avatar answered Feb 01 '26 12:02

Tobias Steely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!