线性排序搜索

时间:2015-12-14 22:23:10

标签: java arrays methods linear-search

我创建了这个代码,这是一个图表位置。它应该允许用户输入已在数组中设置的名称,并且输入不是“结束”时艺术家的位置将输出

public static void main(String[] args) {
    Scanner kybd = new Scanner (System.in);
    String names = null;

    String [] Artists = new String [];
    String [] Artists = new String []{"Fetty Wap", "Drake", "Miley Cyrus"
    ,"Kanye West","Chris Browna","Tinie Tempah","Robin Thicke","The Weeknd"
    ,"Jay Z","The Wanted"};

    do{
        System.out.println("Please enter name ");
        names = kybd.next();
    } while (!names.equalsIgnoreCase("end")) ;
}

public static int linearSorted(int[] array, int item)
{
    int index = 0;
    while (index < array.length &&
    array[index] != item &&
    array[index] < item)
    {
        index++;
    }

    if (index == array.length ||
    array[index] > item)
    {
        index = -1;
    }
    return index;
}
} 

我遇到的问题是它没有显示图表位置,因为它在数组中排序

1 个答案:

答案 0 :(得分:0)

如果您只需要线性搜索来查找名称索引,那么这应该可以正常工作

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String name = null;
    String [] Artists = new String []{"Fetty Wap", "Drake", "Miley Cyrus"
            ,"Kanye West","Chris Browna","Tinie Tempah","Robin Thicke","The Weekend"
            ,"Jay Z","The Wanted"};

            do{
                System.out.print("Please enter name: ");
                name = sc.nextLine();
                System.out.println(linearSearch(Artists, name));
            } while (!name.equalsIgnoreCase("end")) ;

}

public static int linearSearch(String[] arr, String name){
    for(int i = 0; i < arr.length; i++){
        if(arr[i].equals(name)){
            return i;
        }
    }
    return -1;
}