Skip to content
Advertisement

JAVA // How do i make it case-insensitive?

import java.util.Random;

public class MergeSortEx {

    public static void mergeSort(char[] array) {
        sortArray(array, 0, array.length);
    }

    private static void sortArray(char[] array, int start, int end) {
        if (end-start <2) 
            return;
    
            int mid = (start + end) / 2;
            sortArray(array, 0, mid);
            sortArray(array, mid, end);
            mergeArray(array, start, mid, end);
    }

    private static void mergeArray(char[] array, int start, int mid, int end) {
        char[] temp = new char[end - start];
        int t = 0, s = start, m = mid;

        while (s < mid && m < end) {
            if (array[s] < array[m])
                temp[t++] = array[s++];
            else
                temp[t++] = array[m++];
        }

        while (s < mid) {
            temp[t++] = array[s++];
        }
        while (m < end) {
            temp[t++] = array[m++];
        }
        
        for(int i=start;i<end;i++) {
            array[i]=temp[i-start];
        }
    }

    public static void main(String[] args) {
        char[] randomString = new char[20];
        Random rnd = new Random();

        for (int i = 0; i < 20; i++) {
            if (i < 10)
                randomString[i] = (char) (rnd.nextInt(6) + 'A');
            else
                randomString[i] = (char) (rnd.nextInt(6) + 'a');
        }

        System.out.println(randomString.length);
        for (int i = 0; i < 20; i++)
            System.out.print(randomString[i] + " ");
        
        mergeSort(randomString);
        System.out.println();
        for (int i = 0; i < 20; i++)
            System.out.print(randomString[i] + " ");
    }
}

I used the translator. It’s a university algorithm assignment, Merge sort implemented successfully. Now, capital letters come out first, and lowercase letters come out. Can make the code case-insensitive? I want the results to be like this. ex) a A A B b C c c D d … plz help.

Advertisement

Answer

Instead of comparing using if (array[s] < array[m]) directly, convert the characters to uppercase before comparing, similar to what String.compareToIgnoreCase(...) does:

if (Character.toUpperCase(array[s]) < Character.toUpperCase(array[m]))

That is for sorting individual characters. For sorting String values, there are two ways to make a case-insensitive sort:

  1. Use the predefined String.CASE_INSENSITIVE_ORDER Comparator.

    stringList.sort(String.CASE_INSENSITIVE_ORDER);
    
  2. Use a Collator:

    Collator collator = Collator.getInstance(Locale.US);
    stringList.sort(collator);
    

    That will sort localized alphabets correctly, e.g. if you specified Locale.GERMANY, it would sort upper- and lower-case letters together, but will e.g. also sort Ð between D and E, and sort ß same as S.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement