简体   繁体   中英

Bubble Sort Array with unknown length (Java)?

This is Java through my university so there are some components in here that you may not know. Do not pay attention for them because they are not the problem.

My compiler made me initialize my array to null. I then try to run the rest of my program and it said that it is supposed to work with an array that has actual values in it. My question is how should I go about doing this?

private static String[] alphabetSort(Map<String, Integer> mapWord) {

    String[] ordered = null;

    Map<String, Integer> copy = mapWord;

    for (int i = 0; i < copy.size(); i++) {
        Map.Pair<String, Integer> pair = copy.removeAny();
        String key = pair.key();
        ordered[i] = key;
    }

    boolean flag = true;
    String temp;

    while (flag) {

        flag = false;

        for (int j = 0; j < ordered.length; j++) {

            String test1 = ordered[j];
            String test2 = ordered[j + 1];

            if (test1.compareTo(test2) < 0) {
                temp = ordered[j];
                ordered[j] = ordered[j + 1];
                ordered[j + 1] = temp;
                flag = true;
            }
        }
    }

    return ordered;
}

Arrays have fixed-size . You have to pick a size when you're creating it.

Try:

String[] ordered = new String[mapWord.size()];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM