2011-11-09 163 views
0

我正在嘗試編寫一個程序,該程序在名爲items的數組中執行順序搜索和二進制搜索,該數組具有10000個已排序的隨機int值。稱爲targets的第二個數組加載了1000 int值(來自items陣列的500個值和不在items陣列中的500個值)。二進制/順序搜索

基本上,搜索需要通過items數組來查找targets數組中的int值。這是我的代碼:

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

編輯:輸出應該是這樣>

-1

-1

順序搜索時間:40毫秒

-1

-1

二進制搜索時間:0毫秒

回答

2

sequentialSearch都是錯誤的,你甚至不訪問它中的數組。

這兩個搜索方法調用loadItemsAndTargets。它只能被調用一次

binarySearch只適用於排序的數組。你的數組沒有排序。

即使你糾正了所有這些錯誤。注意你的數組將包含重複項。因此,如果試圖索引sequentialSearch之間比較的binarySearch他們可能不匹配,除非你的binarySearch返回下界

+0

我忘了提及...我在初學者的java類。我絕對堅持要做什麼...... – user1036862

+1

在尋求幫助之前,您必須首先嚐試。你有什麼問題? –

+0

我通過在我的binarySearch方法中不調用loadItemsAndArray方法更改了我的代碼。然後我嘗試使用Array.sort對數組進行排序,但它給了我一個編譯器錯誤,說排序是未定義的類型數組... – user1036862

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. 

順序搜索的好處是,你的產品最終會被發現,即使名單沒有排序。二進制搜索的優點是您可以更快地找到您的物品,但是必須對列表進行排序。例如,一百萬個項目列表將平均需要五十萬次比較才能通過順序搜索找到一個項目;但是,二分查找只需要大約二十個比較。這是因爲二進制搜索中的每個比較都拋棄了剩餘可能性的一半,而順序搜索中的每個比較只會拋出一種可能性。

+0

註釋的情況,您首先將鍵設置爲等於目標。稍後,您會檢查它們是否相同,以確定是否找到該項目。把這兩樣東西放在一起會讓你找到一切,即使這些物品不在列表中! –

+0

我試過了:if(key == items [target])found = true; – user1036862