Problem statement: how do you find the largest element in an array?
Method-I:
Method-I:
- public class LargestElementInArray{
- public static void main(String[] args) {
- int a[] = { 60, 65, 70, 55, 45, 80 };
- int max = a[0];
- int length = a.length;
- for(int i=0; i<length; i++){
- if(max < a[i]){
- max = a[i];
- }
- }
- System.out.println(max);
- }
- }
Output: 80
Time complexity: O(n)
Method-II:
Time complexity: O(n/2)
Time complexity: O(n)
Method-II:
- public class LargestElementInArray {
- public static void main(String[] args) {
- int a[] = { 60, 65, 70, 55, 45, 80 };
- int max = a[0];
- int length = a.length;
- int end = a.length - 1;
- for (int i = 0; i < length / 2; i++) {
- if (max < a[end]) {
- max = a[end];
- }
- if (max < a[i]) {
- max = a[i];
- }
- }
- System.out.println(max);
- }
- }
Time complexity: O(n/2)
No comments:
Post a Comment