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?
Given an array of positive or negative integer. How will you write an algorithm to find out the smallest element in the given array?
- public class SmallestElement {
- public static void main(String[] args) {
- int a[] = { 3, 4, 1, 5, 0, -10, -40 };
- int min = Integer.MAX_VALUE; // 2147483647
- for (int i = 0; i < a.length; i++) {
- if (a[i] < min) {
- min = a[i];
- }
- }
- System.out.println("min: " + min);
- }
- }
Output:
min: -40
No comments:
Post a Comment