2016-07-31 84 views
1

如果我搜索我的排序數組,它只會顯示其中一個值,即使數組中有多個相同的值。我不想告訴我有多少重複,我希望它顯示我搜索的數組中的所有重複值。還是有不同的搜索我需要用來做到這一點?C#獲取二進制搜索以顯示數組中的所有重複值

所以,如果我有數組1 {1,2,3,4,4,5,5,5,5,6},我尋找5 I希望它輸出:

5 
5 
5 
5 

這是是我的二進制搜索代碼。

public class search 
    { 
    public static void Main(string[] args) 
    { 
     //Arrays are created here. e.g. array1{1,2,3,4,4,5,5,5,5,6} 

     int Input; 

    Console.WriteLine("Enter the number you would like to search for."); 
    Input = Convert.ToInt32(Console.ReadLine()); 
    int y = BinarySearch(array1, Input); 
Console.WriteLine("array1 {0} : array2{1} : array3 {2} : array4 {3} : array5 {4}",array1[y], array2[y], array3[y], array4[y], array5[y]); 
}  

public static int BinarySearch(double[] Array, int Search) 
     { 
      int x = Array.Length; 
     int low = 0; 
     int high = x - 1; 

     while (low <= high) 
     { 
      while (low <= high) 
      { 
       int mid = (low + high)/2; 
       if (Search < Array[mid]) 
       { 
        high = mid - 1; 
       } 
       else if (Search > Array[mid]) 
       { 
        low = mid + 1; 
       } 
       else if (Search == Array[mid]) 
       { 
        Console.WriteLine("{0}", Search); 
        return mid; 
       } 
      } 
      Console.WriteLine("{0} was not found.", Search); 
     } 
     return high; 
     } 
} 
+0

你有這樣的'return'聲明第一場比賽 –

回答

0

當然,您可以使用二進制搜索。但是你的代碼有點奇怪。因爲當你在這裏找到第一個元素else if (Search == array[mid]) ...時,你立即從該函數返回並且不再調用它。這就是爲什麼你只能得到一個結果。

爲了使它工作,當你找到這樣的元素時,你需要通過索引low ... mid-1然後通過索引mid + 1 ... high來搜索數組。

下面是代碼,但我強烈建議你不要只是複製,也許嘗試改寫成while循環(每個遞歸可以改寫爲一個循環)

static void BinarySearch(int[] array, int low, int high, int searchedValue) 
    { 
     if (low > high) 
      return; 
      int mid = (low + high)/2; 
      if (searchedValue < array[mid]) 
      { 
       high = mid - 1; 
       BinarySearch(array, low, high, searchedValue); 
      } 
      else if (searchedValue > array[mid]) 
      { 
       low = mid + 1; 
       BinarySearch(array, low, high, searchedValue); 
      } 
      else if (searchedValue == array[mid]) 
      { 
       Console.WriteLine(array[mid]); 
       BinarySearch(array, low, mid - 1, searchedValue); 
       BinarySearch(array, mid + 1, high, searchedValue);    
      }    
    }