This post presents a Python solution to find the median in a given integer array. The algorithm efficiently calculates the median, which represents the middle value in a sorted array, or the average of the two middle values for arrays with an even number of elements.

By implementing this Python code, you can easily determine the median of any integer array


def find_median(arr):
    sorted_arr = sorted(arr)
    n = len(sorted_arr)
  
    if n % 2 == 0:
        middle1 = sorted_arr[n // 2 - 1]
        
        middle2 = sorted_arr[n // 2]
        
        median = (middle1 + middle2) / 2
    else:
        median = sorted_arr[n // 2]

    return median

usage:


array = [7, 2, 5, 1, 9, 3,7]
median = find_median(array)
print("Median:", median)

Output :

 

Median: 5