Find the smallest element in an array

Problem Statement: Given an array, we have to find the smallest element in the array.

Examples:

Example 1:
Input: arr[] = {2,5,1,3,0};
Output: 0
Explanation: 0 is the smallest element in the array. 

Example2: 
Input: arr[] = {8,10,5,7,9};
Output: 5
Explanation: 5 is the smallest element in the array.

Solution:

Solution1: Sorting

Intuition: हम Array को  Assending  Order में Sort कर सकते है इसलिए smallest element 0th index पर होगा |

Approach: 

  • Array को Assending order में sort कर देंगे
  • 0th index को print कर देंगे

DryRun: 

Before sorting: arr[] = {2,5,1,3,0};

After sorting: arr[] = {0,1,2,3,5};

Hence answer : arr[0] = 0

 Java Code:

import java.util.*;
public class smallest_element {
    public static void main(String args[]) {

        int arr1[] =  {2,5,1,3,0};
        System.out.println("The smallest element in array is: " + sort(arr1));

        int arr2[] =  {8,10,5,7,9};
        System.out.println("The smallest element in array is: " + sort(arr2));
    }
    static int sort(int arr[]) {
        Arrays.sort(arr);
        return arr[0];
    }
}

C++ Code:

import java.util.*;
 
public class DW {
 
  public static void main(String args[]) {
 
    int arr1[] =  {2,5,1,3,0};
    System.out.println("The greatest element in the array is: "+GreatestElement(arr1));
 
    int arr2[] =  {8,10,5,7,9};
    System.out.println("The greatest element in the array is: "+GreatestElement(arr2));
  }
  static int GreatestElement(int arr[]) {
    int max = arr[0];
    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > max) {
        max = arr[i];
      }
    }
    return max;
  }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here