Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

java - Binary Search problem - Help - Trying for hours

I hope you do not mind me posting this up.

I have a problem, and I have been looking at other examples of code from StackOverflow and I still cannot key the correct location on the value I am looking for.

I am to:

//Description: Performs a strong text binary search on an array for a specified value //Parameters: int array of values and int key which item to be searched //Returns: int indicating the first location of the item, or -1 in the case //the key is not found.

It would be greatly appreciated if the simplest and most efficient way of doing this can be solved. Thank you in advance!

My code so far:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BinarySearching

{
public static int binarySearch(int[] array, int key)
{

  int begin = 0;
  int last = array.length -1;
  int mid =0;

  while (begin <= last)
  {
     mid = (begin + last) / 2;

     // Check if key is present at mid
     if (array[mid] < key)
     {
        begin = mid +1;
     }

     // If key greater, ignore left half
     else if (array[mid] > key)
     {
        last = mid - 1;
     }
        // If x is smaller, ignore right half
     else
     {
        return mid;
     }
  }

  // if we reach here, then element was
  // not present

  if(last == 0)
  {
     return -1;
  }

  return mid;
}

public static void main(String[] args)
{

  int[] numbers = readArrayFromFile("practice_data.txt");


  int key = 3555318 ;

  int result = binarySearch(numbers, key);

  if (result == -1)
  {
     System.out.println("Element not present " +result);
  }
  else
  {
     System.out.println("Element found at "
           + "index " + result);
  }

}//main
}//class

/////////////////////////////////////////////////////////////////////////////////

Sample of text file. This would on my intellj be going to the next line after each number is entered.

Example: 1 2 3 4

Sample from Text file:

10000 -6335552 2276239 -9496279 -2570465 -3131620 6185632 6080225 -8641474 802221 4654808 -6425849 1001941 -1884575 3555318 3555318 3555318 2280363 -5578898 -1843525 2106946 1142271 5735601 6551052 -1367885 3972930 -5147855 6901888 9999313 -443147 5700530 9439329 -4407250 8461347


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...