0

items10000個のソートされたランダムint値を持つ配列でシーケンシャル検索とバイナリ検索を実行するプログラムを作成しようとしています。呼び出された 2 番目の配列には、1000 個の値 (配列からの500 個の値と、配列にない 500個の値)targetsがロードされます。intitemsitems

int基本的に、検索では配列内の値を探すために項目配列を通過する必要がありますtargets。これは私のコードです:

  import java.util.*;

 // Loads two arrays with integers
 // Searches the arrays using sequential search and binary search
 // Compares the time for each search

public class Searches {

private int items[], targets[];

public Searches() { 

    this.items = new int[10000];
    this.targets = new int[1000];
}

public void loadItemsAndTargets(){

    int nextValue = 100;
    int index = 0;

    Random generator = new Random(1); 

    items[0] = nextValue;

    /* load the items array with items to be searched through */

    for (index = 1; index < items.length; index++){
        nextValue = nextValue + generator.nextInt(100);
        items[index]= nextValue;
    }

    /* load the targets array with target values that will be searched for within
     * array items, and target values that are not within array items
     */

    index = 0;

    while (index < targets.length){
        targets[index] = items[index*10];
        targets[index+1] = generator.nextInt(100);
        index = index + 2;
    }      
}

public int sequentialSearch(int target) {
    /* Using the sequential search algorithm, search the items array for the target value passed
     * If found, return the index in the items array, otherwise return -1
     */
    this.loadItemsAndTargets();

    int key = target;
    int index;

    boolean found = false;

    index = 0;
    while ((!found) && (index < items.length)) 
        if (key == target)
            found = true;
        else
            index = index + 1;

    if (!found) 
        index = -1;
    return index;
}       

public int binarySearch(int target){
    /* Using the binary search algorithm, search the items array for the target value passed
     * If found, return the index in the items array, otherwise return -1
     */
    this.loadItemsAndTargets();


    target = targets.length;
    int key = target;
    boolean found = false;
    int guess = 0;
    int low = 0;
    int high = items.length - 1;
    while ((!found) && (low < high)) {
        guess = (high+low)/2;
        if (key == items[guess]) 
            found = true;
        else if (key < items[guess])
            high = guess - 1;
        else
            low = guess + 1;

        if (!found)
            return - 1;
    }

   return guess;
}
public static void main(String[] args) {
    int index = 0;
    Searches searcher = new Searches();
    searcher.loadItemsAndTargets();

    /* call the method that searches array items 
     * for each of the values in array targets
     * using the sequential search algorithm
     * print the approximate elapsed time in milliseconds
     * For the FIRST FIVE searches print out the index 
     * where target value was found or print -1 if it was not found 
     */


    long startTimeSequential;
    startTimeSequential  = System.currentTimeMillis();

    System.out.println(searcher.sequentialSearch(index));

    long endTimeSequential;
    endTimeSequential = System.currentTimeMillis();

    long totalTimeSequential;
    totalTimeSequential = endTimeSequential-startTimeSequential;
    System.out.println("sequential search time: " + totalTimeSequential + " milliseconds");

    /* call the method that searches array items
     * for each of the values in array targets
     * using the binary search algorithm
     * print the approximate elapsed time in milliseconds
     * For the FIRST FIVE searches print out the index 
     * where target value was found or print -1 if it was not found 
     */
    long startTimeBinary;
    startTimeBinary = System.currentTimeMillis();

    System.out.println(searcher.binarySearch(index));

    long endTimeBinary;
    endTimeBinary = System.currentTimeMillis();

    long totalTimeBinary;
    totalTimeBinary = endTimeBinary - startTimeBinary;
    System.out.println("binary search time: " + totalTimeBinary + " milliseconds");
 }      
}   

編集:出力はこれでなければなりません>

395

986

-1

14

-1

シーケンシャル検索時間: 40 ミリ秒

395

986

-1

14

-1

バイナリ検索時間: 0 ミリ秒

4

2 に答える 2

2

あなたのsequentialSearchはすべて間違っています。その中の配列にアクセスしていません。

検索メソッドは両方ともloadItemsAndTargetsを呼び出します。一度だけ呼び出す必要があります

binarySearchは、並べ替えられた配列でのみ機能します。配列はソートされていません。

これらの間違いをすべて修正したとしても。配列には重複が含まれることに注意してください。したがって、シーケンシャルサーチとバイナリサーチの間でインデックスを比較しようとすると、バイナリサーチが下限を返さない限り、一致しない可能性があります

于 2011-11-09T04:12:10.490 に答える
1

手元にある検索手法を非常によく理解していると、コードを書くのが簡単になる場合があります。それを念頭に置いて、うまく説明されていない場合に備えて、おそらく聞いたことがあることを繰り返します.

順次検索は単純です。

1. Set the starting index just before the beginning.
2. If there is a "next" item, check the next item to see if it matches.  
2a. If it does match you found the item in your collection.
2b. If it does not match update the starting index to the item you just checked and continue at step 2.
3. If there is no next item, then you searched everything without finding your item.

二分探索も簡単です。

1. If the unsearched part of your list is empty, then determine you didn't find the item.
2. If the unsearched part of your list is just one element, then check the element to see if it matches the lookup item.
2a. If id does match, you found the item in your list.
2b. If it does not match, the item isn't in your list.
3. If the unsearched part of your list is more than one element, find the element closest to the middle. It is ok to divide two element lists like {2, 4} into {2} 4 {} where 4 is the middle.
3a. If the middle matches the lookup item, you found the item in your list.
3b. If the middle is larger than the lookup item, select the "smaller" side list and repeat the process.
3c. If the middle is smaller than the lookup item, select the "larger" side list and repeat the process.

シーケンシャル検索の利点は、リストがソートされていなくても、アイテムが最終的に見つかることです。二分検索の利点は、項目をより速く見つけることができることですが、リストをソートする必要があります。たとえば、100 万個のアイテム リストを順次検索してアイテムを見つけるには、平均で 50 万回の比較が必要です。ただし、二分探索では約 20 回の比較しか必要ありません。これは、二分探索の各比較では残りの可能性の半分が破棄されるのに対し、逐次探索の各比較では 1 つの可能性のみが破棄されるためです。

于 2011-11-09T04:36:12.390 に答える