java - 如何通过二分搜索搜索 ArrayList 中的任何值

标签 java binary-search

由于获取键值,我在获取包含许多索引的列表时遇到问题。我的代码中有一个错误。

我的城市类别如下所示。

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

我的数组列表包含城市名称及其国家/地区名称,如下所示。

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);
    }

最佳答案

这将使用城市名称进行搜索

    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

关于java - 如何通过二分搜索搜索 ArrayList 中的任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410108/

相关文章:

algorithm - 将 B 个芝士蛋糕分给 N 个类(class),以尽量减少每个蛋糕的最大学生人数

java - NoSuchElementException : No line found when getting user input with scanner?

java - 添加字符串长度时遇到问题

java - 错误: incompatible types: int cannot be converted to Client - Java

java - 为您的 Cloud Endpoints 类生成 API 元数据失败

go - 两种算法,我的机器上的结果相同,测试上的结果不同

c - c中删除二叉树根节点的迭代方法

java - Java 中的工作流 UI

java - 为什么可写数据类型应该是可变的?

algorithm - 如何从建筑物中扔出 2 个鸡蛋并用 ~c*sqrt(F) throws 找到 F 层?