The Wayback Machine - https://web.archive.org/web/20241005041528/https://www.geeksforgeeks.org/binary-search-on-java-vector/
Open In App

Binary Search on Java Vector

Last Updated : 16 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Vector is a legacy class in Java and is present from Java 1.2 version. It implements the List interface of the Collection framework and is found in java.util package. Vector is just like an array that can grow dynamically. Vectors are synchronized ie vectors are thread-safe. Vectors are mainly used where thread synchronization is of utmost importance. In other cases, ArrayList performs better. Since vector is a legacy class in Java, the elements in a vector can be iterated over by Enumeration only. In this article, we shall see a binary search operation on a vector. Binary search is a search technique in which a sorted array is repeatedly divided into half and the middle element is checked for the target element. To search a target element in a vector we will be using the binarySearch() method of the Collections class.

Syntax:

binarySearch(List list, Object target)

Parameters: 

  • The List type object on which binary search is to be performed.
  • The value of the target element.

Return Value: Returns the index of the target element if it is found else returns -1.

Example:

Java




// Java Program to Demonstrate Binary Search on Vector
 
// Importing utility classes
import java.util.*;
 
// Main class
// BinarySearchOnVector
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a Vector by
        // declaring integer object of Vector class
        Vector<Integer> v = new Vector<>();
 
        // Adding elements to Vector
        // using add() method
        v.add(10);
        v.add(50);
        v.add(20);
        v.add(40);
        v.add(25);
 
        // Note: Binary search works only on sorted list
 
        // Sorting the above vector
        // using sort() method of Collections class
        Collections.sort(v);
 
        // Searching an element using binarySearch() method
        // of Collections class
        int index = Collections.binarySearch(v, 25);
 
        // Printing the position of the target
        System.out.println("Element is found at index : "
                           + index);
    }
}


Output

Element is found at index : 2

Output Explanation: The vector elements were not added in the sorted order. Since binary search works only on the sorted list, we sort the vector first and then perform a binary search. The target is found at index 2 and hence the value is returned and printed.

Time Complexity: O(log n) where ‘n’ is the size of the vector.

Example 2:

Java




// Java Program to Demonstrate Binary Search on Vector
 
// Importing required classes
import java.util.*;
 
// Main class
// BinarySearchVector
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a Vector by
        // declaring object of Vector class of string type
        Vector<String> v = new Vector<>();
 
        // Adding elements to Vector
        // using add() method
        v.add("10");
        v.add("B");
        v.add("20");
        v.add("A");
        v.add("25");
 
        // Note: Binary search works only on sorted list
 
        // Sorting the above vector elements using
        // sort() of Collections class
        Collections.sort(v);
 
        // Printing the sorted elements of above vector
        System.out.println("Sorted Vector: " + v);
 
        // Searching an element using binarySearch method
        // of Collections class
        int index = Collections.binarySearch(v, "25");
 
        // Printing the position of target on console
        System.out.println("Element is found at index : "
                           + index);
    }
}


Output

Sorted Vector: [10, 20, 25, A, B]
Element is found at index : 2

Output explanation: The numeric strings are positioned before the alphabetic strings. Now the target string 25 lies at index 2 and hence the value is returned and printed.

Time Complexity: O(log n) where ‘n’ is the size of the vector. 



Similar Reads

Copy Elements of One Java Vector to Another Vector in Java
Vector is similar to arrays but is growable also, or we can say no fixed size is required. Previously vector was a part of legacy classes but now it is part of Collections. It also implements a List interface, so we can use any method of list interface on vectors also. Syntax : Vector<Integer> gfg=new Vector<>(); Ways To copy elements o
3 min read
Java Program to Search ArrayList Element Using Binary Search
Linear Search can be implemented for sorting and non-sorting elements of a Data structure particular Data structure but the average case time complexity is O(n). Whereas as Binary Search can be implemented only when the items are in sorted order and average-case time complexity is O(logn) and both Transversal have best-case Time complexity is O(1).
3 min read
Java Program to Search User Defined Object From a List By Using Binary Search Using Comparator
The Comparator interface in Java can be used to compare user-defined objects. The Comparator interface is present in java.util package. Binary search is a searching algorithm that uses the divide and conquers rule to search the presence of an element in a list or array. The binary search algorithm works only on a sorted list. In case the list is no
6 min read
Java Program to Search an Element in Vector
A vector in Java is a dynamic array that can be resized as needed. It is synchronized, which means it is safe in multi-threaded programs. To find an element in a Vector we have to loop through its elements to find a match. In this article, we will learn how to search for a component in a Vector using Java. Methods to Search an Element in VectorUsin
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Java Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Java Program for Binary Search (Recursive and Iterative)
So as we all know binary search is one of the searching algorithms that is most frequently applied while dealing with data structures where the eccentric goal is not to traverse the whole array. Here array must be sorted as we check the middle element and ignore the half of the array which is of no use as per the number system. We basically ignore
4 min read
Java Program to Perform Binary Search on ArrayList
The ArrayList class is a part of the collection framework and is present in java.util package. It provides us with resizable or dynamic arrays in java. It is quite slower than standard arrays but can be helpful in some programs where we need to come up with cleaner and shorter code and lots of manipulation of an array is needed. The most effective
6 min read
Java Program to Find the Cube Root of a Given Number Using Binary Search
Given a non-negative number find the cube root of a number using the binary search approach. Examples : Input: x = 27 Output: 3 Explanation: The cube root of 16 is 4. Input: x = 120 Output: 4 Explanation: The cube root of 120 lies in between 4 and 5 so floor of the cube root is 4.Naive Approach: Check the cube of every element till n and store the
2 min read
Java program to Find the Square Root of a Number using Binary Search
Given a non-negative number find the square root of a number using the binary search approach. Examples : Input: x = 16 Output: 4 Explanation: The square root of 16 is 4. Input: x = 5 Output: 2 Explanation: The square root of 5 lies in between 2 and 3 so floor of the square root is 2. Naive Approach: Check the square of every element till n and sto
3 min read
Binary Search vs contains Performance in Java List
Java provides two methods namely Collections.binarySearch() and contains() to find an element inside a list. Underneath the hood, contains() method uses indexOf() method to search for the element. indexOf() method linearly loops through the List and compares every element with the key until the key is found and returns true otherwise it returns fal
6 min read
Binary Search in Java
Binary search is one of the searching techniques applied when the input is sorted here we are focusing on finding the middle element that acts as a reference frame whether to go left or right to it as the elements are already sorted. This searching helps in optimizing the search technique with every iteration is referred to as binary search and rea
6 min read
Java Program to Construct a Binary Search Tree
Binary Search Tree (BST) is the widely used data structure in computer science, primarily known for the efficient search, insertion, and deletion operations. It is the type of binary tree where each node has at most two children, referred to as the left child and the right child. Binary Search Tree offers the efficient average-case time complexity
6 min read
Repeatedly search an element by doubling it after every successful search
Given an array "a[]" and integer "b". Find whether b is present in a[] or not. If present, then double the value of b and search again. We repeat these steps until b is not found. Finally we return value of b. Examples: Input : a[] = {1, 2, 3} b = 1 Output :4 Initially we start with b = 1. Since it is present in array, it becomes 2. Now 2 is also p
6 min read
Vector clear() Method in Java
The Java.util.Vector.clear() method is used to remove all the elements from a Vector. Using the clear() method only clears all the element from the vector and does not delete the vector. In other words, we can say that the clear() method is used to only empty an existing vector. Syntax: Vector.clear() Parameters: The method does not take any parame
2 min read
Vector addAll() Method in Java
java.util.Vector.addAll(Collection C): This method is used to append all of the elements from the collection passed as a parameter to this function to the end of a vector keeping in mind the order of return by the collection's iterator. Syntax: boolean addAll(Collection C) Parameters: The method accepts a mandatory parameter C which is a collection
2 min read
Sort Java Vector in Descending Order Using Comparator
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of the List interface. There are two types of Sorting technique: First is internal sorting i.e that uses
3 min read
Vector set() Method in Java
The Java.util.Vector.set() method is used to replace any particular element in the vector, created using the Vector class, with another element. Syntax: Vector.set(int index, Object element) Parameters: This function accepts two mandatory parameters as shown in the above syntax and described below. index: This is of integer type and refers to the p
2 min read
Vector isEmpty() Method in Java
The Java.util.Vector.isEmpty() method in Java is used to check and verify if a Vector is empty or not. It returns True if the Vector is empty else it returns False. Syntax: Vector.isEmpty() Parameters: This method does not take any parameter. Return Value: This function returns True if the Vectoris empty else it returns False. Below programs illust
2 min read
Vector lastIndexOf() Method in Java
The Java.util.Vector.lastIndexOf(Object element) method is used to check and find the occurrence of a particular element in the vector. If the element is present in the vector then the lastIndexOf() method returns the index of last occurrence of the element otherwise it returns -1. This method is used to find the last occurrence of a particular ele
2 min read
Vector addElement() Method in Java
The Java.util.Vector.addElement() method is used to append a specified element to the end of this vector by increasing the size of the vector by 1. The functionality of this method is similar to that of the add() method of Vector class.Syntax: boolean addElement(Object element) Parameters: This function accepts a single parameter element of object
2 min read
Vector subList() Method in Java
The java.util.Vector.subList() is used to return a sublist of the existing Vector within a range mentioned in the parameter. The method takes in an upper limit and a lower limit and returns all the elements mentioned in the range. The lower limit is included if the element is present in the list and the upper limit is excluded. Basically, it takes
3 min read
Vector add() Method in Java
boolean add(Object element): This method appends the specified element to the end of this vector. Syntax: boolean add(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the vector. Return Value: This method returns True after succes
2 min read
Vector capacity() Method in Java
The Java.util.Vector.capacity() method in Java is used to get the capacity of the Vector or the length of the array present in the Vector. Syntax: Vector.capacity() Parameters: The method does not take any parameter. Return Value: The method returns the capacity or the internal data array’s length present in the Vector, which is an integer value. B
2 min read
Vector contains() Method in Java
The java.util.vector.contains() method is used to check whether a specific element is present in the Vector or not. So basically it is used to check if a vector contains any particular element or not. Syntax: Vector.contains(Object element) Parameters: This method takes a mandatory parameter element which is of the type of vector. This is the eleme
2 min read
Vector containsAll() Method in Java
The java.util.vector.containsAll() method is used to check to check if this Vector contains all of the elements in the specified Collection. So basically it is used to check if a vector contains a set of elements or not. Syntax: Vector.containsAll(Collection col) Parameters: This method accepts a mandatory parameter col which is of the type of vect
2 min read
Vector copyInto() Method in Java
The java.util.vector.copyInto() method is used to copy all of the components from this vector to another array, having enough space to hold all of the components of the vector. It is to be noted that the index of the elements remains unchanged. The elements present in the array are replaced by the elements of the vector. Syntax: Vector.copyInto(Obj
2 min read