Finding Minimum Element of Java Vector
Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. We know two ways for declaring array i.e. either with a fixed size of array or size enter as per the demand of the user according to which array is allocated in memory.
int Array_name[Fixed_size] ; int array_name[variable_size] ;
In both ways, we land up wasting memory so, in order to properly utilize memory optimization, Vectors were introduced.
We need to find out the minimum element in the given java vector.
Input: [1,2,3,4,5] Output: 1 Input: [88,23,76,90,56] Output: 23
Approach 1: Using a Predefined Function
- To find the minimum element of a given vector we use the java.util.Collections.min() method.
- This directly finds the minimum value in the vector.
Vector elements: [1, 2, 3, 4, 5] The maximum element of the Vector is: 1
Worst Case Time Complexity: O(n) where n is the number of elements present in the vector.
Approach 2: Comparing each element present in Vector
- First, we will initialize a vector let’s say v, then we will store values in that vector.
- Next, we will take a variable, let us say minNumber and assign the minimum value possible.
- Traverse till the end of vector and compare each element of a vector with minNumber.
- If the element present in the vector is less than minNumber, then update minNumber to that value.
- Print minNumber.
The smallest element present in Vector is : 10
Time Complexity: O(n) where n is the number of elements present in the vector.