Thursday, February 4, 2021

How to find smallest item in the array within constant time complexity

	
    
public class SmallestItemIntoArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[] = {1,8,10,40,30,60,50,0,-2}; 
        
		System.out.println("The smallest Item is : "+
        	new SmallestItemIntoArray().smallestItem(arr));
	}

	public int smallestItem(int arr[]) {
		int smallest=0;
		for (int i : arr) {
			
			if(smallest==0) {
				smallest=i;
			}
			if(smallest > i) {
				smallest = i;
			}
		}
		return smallest;
	}
}


Output:-
The smallest Item is : -2
    

No comments:

Post a Comment

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...