Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.


Collection Classes

Binary Search by FredrikN
Posted: 18 Apr 03 (Edited 18 Apr 03)

This is very important to learn.

Binary searching is a very very effective search metod.

A binary search locates a value by determining if the first or second half, the repeting the search in one of the halves, therefor binary search is an O(log(N)) algoritm.

public class Main

    private static LinkedList lista = new LinkedList();
    private static int[] a = new int[10000000+1];

    public static void main(String[] args)

        for (int i = 0; i <= 10000000; i++)
            a = i;



    public static int search(int v)

        int low = 0;
        int high = a.length - 1;

        while(low <= high)

            int mid = (low + high) / 2;
            int diff = a[mid] - v;

            if(diff == 0)
              return mid;

            else if(diff < 0)
               low = mid + 1;

                high = mid - 1;

        return -1;

public class LinkedList
    private IntNode head;

    public LinkedList()
        head = null;

    public void add (int data)
        IntNode nyNode = new IntNode(null, data);
        IntNode current;

        if (head == null)
            head = nyNode;

            current = head;
            while (current.getNext() != null)
                current = current.getNext();



public class IntNode
    private IntNode next;
    private int data;

    public IntNode(IntNode next, int data)
    { = next; = data;


    public IntNode getNext()
        return next;

    public void setNext(IntNode inNode)
        next = inNode;

    public int getData()
        return data;


Back to Java FAQ Index
Back to Java Forum

My Archive


Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close