Как я могу найти любое значение в ArrayList через бинарный поиск - PullRequest
0 голосов
/ 24 апреля 2020

У меня проблема с получением списка, включающего множество индексов, в результате получения значения ключа. У меня есть ошибка в моем коде.

Класс моего города показан ниже.

public class City implements Serializable{
    private String cityName;
    private String countryName;
    ...
}

Мой Arraylist содержит названия городов и названия стран, как показано ниже.

Shanghai, China
...
...

Поскольку Arraylist очень большого размера, например, 50000, я применяю бинарный поиск для поиска любого символа или слова в списке.

Я хочу найти любой символ или слово, чувствительное к верхнему или нижнему регистру, и получить обратно их индексы. .

Как я могу выполнить этот процесс?

Код выполняется в соответствии с определенным символом, строкой символов или словом, показанным ниже.

Примеры примеров

Enter the word of character which I want to search : W
Enter the word of character which I want to search : Sha
Enter the word of character which I want to search : Shanghai

Вот мой фрагмент кода, показанный ниже.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter the word of character which I want to search : ");
String charWord = scanner.nextLine();
System.out.println("Search " + charWord);
Integer[] index = BinarySearch.binarySearch(cities, charWord);
System.out.println(index.toString());


public static Integer[] binarySearch( ArrayList<City> list, String key ) {
        Comparable comp = (Comparable)key;
        List<Integer> arrlist = new ArrayList<Integer>();
        Integer arr[] = null;
        int res = -1, min = 0, max = list.size() - 1, pos;
        while( ( min <= max ) && ( res == -1 ) ) {
            pos = (min + max) / 2;
            int comparison = comp.compareTo(key.contains(list.get(pos).getCityName()));
            if( comparison == 0) {
                res = pos;
                arrlist.add(res);
            }
            else if( comparison < 0)
                max = pos - 1;
            else
                min = pos + 1;
        }

        return arrlist.toArray(arr);
    }

1 Ответ

1 голос
/ 24 апреля 2020

Поиск будет выполняться по названию города

    private static class City {

        private String country;
        private String cityName;

        public City(String cityName, String country) {
            this.cityName = cityName;
            this.country = country;
        }

        public void setCityName(String cityName) {
            this.cityName = cityName;
        }

        public String getCityName() {
            return cityName;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        @Override
        public String toString() {
            return cityName;
        }
    }

    public static void main(String[] args) {
        List<City> list = new ArrayList<>();
        list.add(new City("Shanghai", "Shanghai"));
        list.add(new City("USA", "USA"));
        list.add(new City("China", "China"));
        list.add(new City("Germany", "Germany"));
        list.add(new City("China", "China"));
        list.add(new City("china", "china"));
        Integer[] indices = binarySearch(list, "China");
        for (int i = 0; i < indices.length; i++) {
            System.out.print(indices[i] + " ");
        }
        System.out.println();
    }

    public static Integer[] binarySearch(List<City> cities, Comparable key) {
        List<Integer> arrList = new ArrayList<Integer>();
        int lo = 0, hi = cities.size() - 1, mid;
        cities.sort((str1, str2) -> str1.getCityName().compareTo(str2.getCityName()));
        System.out.println(cities);
        while (lo <= hi) {
            mid = lo + (hi - lo) / 2;
            int cmp = key.compareTo(cities.get(mid).getCityName());
            if (cmp == 0) {
                arrList.add(mid);
                lo = mid + 1;
            } else if (cmp < 0)
                hi = mid - 1;
            else
                lo = mid + 1;
        }
        return arrList.stream().toArray(Integer[]::new);
    }

    private static Integer[] searchByCharacters(Integer[] indices, List<City> list, String sub) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCityName().contains(sub))
                result.add(i);
        }
        return result.stream().toArray(Integer[]::new);
    }

, вывод

[China, China, Germany, Shanghai, USA, china]
0 1
...