jeudi 25 février 2016

What is wrong with my binary search technique?

I'm in my first Java class in college, and have attempted to do my first assignment involving using the binary search technique. I've created an array to generate 10 random numbers between 1-100, sorted them with a standard for loop (supposed to use the "enhanced for loop"). The last thing to complete successfully besides making my for loop enhanced is to "enter one value, search array using binary search technique to determine if value is present or not and output that. Maybe you guys can help me what I'm doing wrong as I'm getting some errors? Thanks!

import java.util.*;

class lab4point2 //lab4.2 part 1
{
public static void main(String args[])
{

int[] array = new int[10]; //array of 10 numbers created.

Random rand = new Random(); //random class created called rand.

for (int cnt = 0; cnt < array.length; cnt++) //for loop to generate
{array[cnt] = rand.nextInt(100) + 1;}     // the 10 numbers randomly 1-100

Arrays.sort(array); //sorted

System.out.println(Arrays.toString(array));// prints the 10 numbers to screen

System.out.print("Enter a value to see if it is present. ");

Scanner scanner = new Scanner(System.in);
int value = scanner.nextint();

boolean binarySearch(array, 0, 99, value);
{    int size = 100;
     int low = 0;
     int high = size - 1;

    while(high >= low) {
        int middle = (low + high) / 2;
         if(data[middle] == value) {
             System.out.print("Value is present ");
             return true;
         }
         if(data[middle] < value) {
             low = middle + 1;
         }
         if(data[middle] > value) {
             high = middle - 1;
         }
    }
    System.out.print("Value is not present. ");
    return false;
}


}


}




Aucun commentaire:

Enregistrer un commentaire