Slider

Python Program to Find the Smallest Element in an Array.

Given an integer array of size n, the task is to write Python code to find the smallest element present in the given array. Using Python min() Functio
Given an integer array of size n, the task is to write Python code to find the smallest element present in the given array. 

Example:
Input: arr = [2, 6, 1, 3]
Output: Smallest Element: 1

Input: arr = [5, 9, 3, -1, 1]
Output: Smallest Element: 0

There are multiple methods to find the smallest element of an array in Python and here in this tutorial, we will learn two simplest approaches to do so. 

Approach 1: Brute Force (Linear Search)

The linear search technique entails a systematic traversal of the entire array, comparing each element to identify the minimum value.

Algorithm Steps:
  • Begin by setting a variable to the first element.
  • Iterate through each element.
  • For each element, execute a comparison with the current minimum.
  • If a smaller element is discovered, promptly update the minimum.
  • Conclude the process by returning the final minimum.

Python Code:
# Python code to find the smallest element of array
def find_smallest(arr):
    min_element = arr[0]
    for element in arr:
        if element < min_element:
            min_element = element
    return min_element

#function call
arr = [3, 5, -1, 2]
print("Smallest Element:",find_smallest(arr))
Output:
Smallest Element: -1
  • Time Complexity: O(n) where n is the size of the array.
  • Space Complexity: O(1) as no extra space is used.

Approach 2: Using Python min() Function.

Leveraging Python's built-in min() function simplifies the process, directly identifying the minimum element of the array.

Python Code:
# Python code to get the smallest element of the array
def find_smallest(arr):
    return min(arr)

#function call
arr = [3, 5, 0, 2, 1]
print("Smallest Element:",find_smallest(arr))
Output:
Smallest Element: 0
  • Time Complexity: O(n) where n is the size of the array.
  • Space Complexity: O(1) as a constant amount of space is required.
So these are two easy methods to find the smallest element of an array using Python Programming.
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents