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 smallest element in the given array?
  1. public class SmallestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 5, 0, -10, -40 };
  4. int min = Integer.MAX_VALUE; // 2147483647
  5. for (int i = 0; i < a.length; i++) {
  6. if (a[i] < min) {
  7. min = a[i];
  8. }
  9. }
  10. System.out.println("min: " + min);
  11. }
  12. }
Output:
min: -40

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...