Skip to Content

Perform Binary Search on Java Vector Example

  1. /*
  2.   Perform Binary Search on Java Vector Example
  3.   This java example shows how to search an element of Java Vector using
  4.   binarySearch method of Collections class. binarySearch method uses binary
  5.   search algorithm to search an element.
  6. */
  7.  
  8. import java.util.Vector;
  9. import java.util.Collections;
  10.  
  11. public class BinarySearchVectorExample {
  12.  
  13.   public static void main(String[] args) {
  14.     //create a Vector object
  15.     Vector v = new Vector();
  16.  
  17.     //Add elements to Vector
  18.     v.add("A");
  19.     v.add("B");
  20.     v.add("D");
  21.     v.add("E");
  22.     v.add("F");
  23.    
  24.     /*
  25.       To Search an element of Java Vector using binary search algorithm use,
  26.       static int binarySearch(List list, Object element) method of Collections class.
  27.      
  28.       This method returns the index of the value to be searched, if found in the
  29.       Vector.
  30.       Otherwise it returns (- (X) - 1)
  31.       where X is the index where the the search value would be inserted.
  32.       i.e. index of first element that is grater than the search value
  33.       or Vector.size(), if all elements of an Vector are less than the search value.
  34.      
  35.       Please note that the Vector MUST BE SORTED before it can be searched
  36.       using binarySearch method.
  37.     */
  38.    
  39.     //First sort Vector using sort method of Collections class
  40.     Collections.sort(v);
  41.     System.out.println("Sorted Vector contains : " + v);
  42.    
  43.     //search an element using binarySearch method of Collections class
  44.     int index = Collections.binarySearch(v,"D");
  45.    
  46.     System.out.println("Element found at : " + index);
  47.   }
  48. }
  49.  
  50. /*
  51. Output would be
  52. Sorted Vector contains : [A, B, D, E, F]
  53. Element found at : 2
  54. */