1

ソートされた配列で線形に検索し、検索されたアイテムが見つかったさまざまな位置を出力できるプログラムを作成したいと考えています。現時点では、私のプログラムは検索項目が見つかった最初の位置のみを出力するため、私のプログラムが現在行っていることの例を次に示します。

Enter number of elements
5
Enter 5 integers
1
3
3
9
15
Enter value to find
3
3 is present at location 2.

問題は、3 がロケーション 2 と 3 にあり、それをプログラムで編集したいのですが、その方法がわかりません。

私のプログラムのコードは次のとおりです。

import java.util.Scanner;
 class LinearSearchArray1 {
    public static void main(String args[]){
        int c, n, search, array[];

        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of elements");
        n = in.nextInt(); 
        array = new int[n];

        System.out.println("Enter " + n + " integers");

        for (c = 0; c < n; c++)
        array[c] = in.nextInt();

        System.out.println("Enter value to find");
        search = in.nextInt();

        for (c = 0; c < n; c++)
        {
            if (array[c] == search)     /* Searching element is present */
            {
             System.out.println(search + " is present at location " + (c + 1) + ".");
            break;
        }
    }
    if (c == n)  /* Searching element is absent */
        System.out.println(search + " is not present in array.");
    }
}
4

4 に答える 4

1

このコードはあなたのために働くかもしれません。

    int c = 0;

    while (c < array.length && array[c] < search)
    {
        cc++;
    }
    int first = c;
    while (c < array.length && array[c] == search) {
        c++;
    }
    int last = c;

インデックス "first" と "last" の間の要素 (それらを含む) には、検索された番号が含まれます。したがって、基本的には、探しているものと同じ最初と最後の要素を検索します。
コンソールに書き込む例:

    for (int i = first; i <= last; i++)
    {
        System.out.println(search + " is present at location " + (i + 1) + ".");
    }
于 2015-12-24T12:52:39.233 に答える