Tuesday, June 26, 2018

How do you find largest element in an array ?

Problem statement: how do you find the largest element in an array?

Method-I:
  1. public class LargestElementInArray{
  2. public static void main(String[] args) {
  3. int a[] = { 60, 65, 70, 55, 45, 80 };
  4. int max = a[0];
  5.   int length = a.length;
  6. for(int i=0; i<lengthi++){
  7. if(max a[i]){
  8. max = a[i];
  9. }
  10. }
  11. System.out.println(max);
  12. }
  13. }
Output: 80
Time complexity: O(n)

Method-II:
  1. public class LargestElementInArray {
  2. public static void main(String[] args) {
  3. int a[] = { 60, 65, 70, 55, 45, 80 };
  4. int max = a[0];
  5. int length = a.length;
  6. int end = a.length - 1;
  7. for (int i = 0; i < length / 2; i++) {
  8. if (max < a[end]) {
  9. max = a[end];
  10. }
  11. if (max < a[i]) {
  12. max = a[i];
  13. }
  14. }
  15. System.out.println(max);
  16. }
  17. }
Output: 80
Time complexity: O(n/2)

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...