Saturday, August 24, 2019

How will you find smallest element in an array?

Problem statement:
Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the given array?
  1. public class LargestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 5, 0, -10 };
  4. int max = Integer.MIN_VALUE;  //-2147483648
  5. for (int i = 0; i < a.length; i++) {
  6. if (a[i] > max) {
  7. max = a[i];
  8. }
  9. }
  10. System.out.println("max: " + max);
  11. }
  12. }
Output:
max: 5

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...