2014-12-03 2 views
1

Это метод, который ищет целевой номер в RandomAccessFile, используя двоичный поиск. Он касается исключительно целых чисел. У меня есть все настройки, но я получаю неправильные цифры. Поскольку raf содержит байты, а целое число содержит четыре байта, я думал, что просто уменьшу высоту на 4 и увеличиваю значение на 4, где одни и те же операции выполнялись 1 в обычном двоичном поиске. По-видимому, это не так, и мне сложно свернуть голову вокруг двоичного ввода-вывода в целом. Помогите?Двоичный поиск RandomAccessFile

//determines if a target number is in a RandomAccessFile using a binary search 
//tracks the number of times it took to find that the number was/wasn't in the file 
public static void binarySearch(){ 
    Scanner input = new Scanner(System.in); 
    int target = 0; //the number being searched for 
    boolean targetFound = false; //indicates if the target is found 
    int searchCount = 0; //the number of times it took to find that the number was/wasn't in the file 

    System.out.print("Please enter the number you wish to search for: "); 

    target = input.nextInt(); 

    try{ 
     RandomAccessFile raf = new RandomAccessFile("Project10.dat", "r"); 
     long low = 0; 
     long high = raf.length() - 1; 
     int cur = 0; 

     while(high >= low){   
      long mid = (low + high)/2; 
      raf.seek(mid); 
      cur = raf.readInt(); 
      System.out.println(cur); //for debugging 

      searchCount++; 

      if(target < cur){ 
       high = mid - 4; 
      } 
      else if(target == cur){ 
       targetFound = true; 
       break; 
      } 
      else{ 
       low = mid + 4; 
      } 
     } 

     raf.close(); 
    } 
    catch(FileNotFoundException e){ 
     e.printStackTrace(); 
    } 
    catch (IOException e){ 
     e.printStackTrace(); 
    } 

    if(targetFound == true){ 
     System.out.println("The number " + target + " is in the file. It took " + searchCount + " tries to discover this."); 
    } 
    else{ 
     System.out.println("The number " + target + " is not in the file. It took " + searchCount + " tries to discover this."); 
    } 

}//end method binarySearch 
+2

Я рекомендую вам не делать этого. Создайте индекс. Я экспериментировал с бинарным поиском файлов десятилетиями назад. Вывод состоял в том, что у нас есть B-деревья. – EJP

+0

Его школьный проект и эти требования. В любом случае, я играл с ним еще немного, и у меня есть работа, хотя я не совсем понимаю это. – PsylentKnight

ответ

1

INT 4 байта так, что ваш файл содержит цифры от 1 ... 20 The The raf.length 80 (не 20), т.е. 4 * 20 У вас есть правильные линии, но необходимо для работы с точки зрения 4 ваша высокая стоимость в этом случае составляет 79, а не 76 (используя пример выше) , поэтому высокая должна быть длиной - 4

Вы можете попробовать: low = 0;

long high = (raf.length()/4) - 1 // this is in terms of elements 

long mid = (low + high)/2 ... again element rather than where in byte array 

raf.seek(mid * 4) // You can use the *4 to access the correct location in bytes 
cur = raf.readInt() 
     if(target < cur){ 
       high = mid - 1; 
      } 
      else if(target == cur){ 
       targetFound = true; 
       break; 
      } 
      else{ 
       low = mid + 1; 
      } 
+0

Интересно, для второй линии у меня есть long high = (raf.length() - 4)/4; И, похоже, сейчас работает. – PsylentKnight

+1

(x - n)/n = x/n - n/n (1) .... так что это одно и то же :) – KevH

Смежные вопросы