Second Largest in array using sorted array ( brute force approach)
Tue Jan 21 2025 19:29:34 GMT+0000 (Coordinated Universal Time)
Saved by
@nithin2003
class Main {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5,6,7,7};
int n = arr.length;//length of the array is n
int largest = arr[n - 1];// the largest is always the last in sorted array
int second_largest = 0;// initaialze a variable for 2nd
for (int i = n - 2; i >= 0; i--) {
if (arr[i] != largest) {
second_largest = arr[i];
break;
}
}
System.out.println("the second largest element:-"+second_largest);
}
}
//required logic in case of array size < 2
// if(arr.length<2){// u can use n variable (n<2)
// System.out.println(" no element in array");
// return ;
// }
//for loop:-
// iteration from the first or second last element , as we are searching for second largest no need to search for n-1 , but we can start from n-1 also , no problem
//This is a brute force approach
//TC=O(nlogn) due to sorting taking more time
//SC=O(n)
content_copyCOPY
Comments