Welcome to the Linux Foundation Forum!

Binary search

This technique uses a binary search to find a target integer in a RandomAccessFile. It is just concerned with integers.
This is the code:

//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

  1. System.out.print("Please enter the number you wish to search for: ");
  2.  
  3. target = input.nextInt();
  4.  
  5. try{
  6. RandomAccessFile raf = new RandomAccessFile("Project10.dat", "r");
  7. long low = 0;
  8. long high = raf.length() - 1;
  9. int cur = 0;
  10.  
  11. while(high >= low){
  12. long mid = (low + high) / 2;
  13. raf.seek(mid);
  14. cur = raf.readInt();
  15. System.out.println(cur); //for debugging
  16.  
  17. searchCount++;
  18.  
  19. if(target < cur){
  20. high = mid - 4;
  21. }
  22. else if(target == cur){
  23. targetFound = true;
  24. break;
  25. }
  26. else{
  27. low = mid + 4;
  28. }
  29. }
  30.  
  31. raf.close();
  32. }
  33. catch(FileNotFoundException e){
  34. e.printStackTrace();
  35. }
  36. catch (IOException e){
  37. e.printStackTrace();
  38. }
  39.  
  40. if(targetFound == true){
  41. System.out.println("The number " + target + " is in the file. It took " + searchCount + " tries to discover this.");
  42. }
  43. else{
  44. System.out.println("The number " + target + " is not in the file. It took " + searchCount + " tries to discover this.");
  45. }

}//end method binarySearch

I've tried everything, but I'm getting the wrong results. Because a raf comprises bytes and an integer contains four bytes, I figured I'd just decrease the high by four and increase the low by four, as described in this blog, where the identical operations were performed by one in a typical binary search. Apparently, this is not the case, and I'm still struggling to understand binary I/O in general. Help?

Answers

  • Posts: 2,238

    Hi @vikash11

    Can you please advise if your post is related to a training course, or to a different Linux topic? This forum is dedicated to a specific initiative, and if you post in the incorrect forum, your post will be overlooked.

    Regards,
    Flavia

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training