# Finding sum of minimum absolute difference of array using Python

## Sum of minimum absolute difference of array

For Finding sum of minimum absolute difference of array using Python we will take median of the given array and find out the absolute difference between median and each element of array and add all together

#### Finding median

we can find median by two methods
1) sort the array in ascending order , and find the middle element . If array length is even median becomes average of array[length/2 -1] and array[length/2] .If array length is odd median will be array[length/2]
2) Using statistics module
Check the image how to find median using first method

• Example 1: Array 11,3,2,4,1 Median-3
• sum=|11-3|+|3-3|+|2-3|+|4-3|+|1-3|
• sum of absolute difference of array=12

## Keypoint

In this section we will learn about basic knowledge which we need to know before coding the above Program. So we must have knowledge of what is an array?

What is an array?
An array is a data structure, it is collection of similar data elements which is stored at contiguous memory locations in which each data element can be accessed directly by only using its index number.

## Algorithm 1:

2.  Sort array in ascending order to find median
3.  According to length of array median of array changes
4.   Subtract the median from each element of the array
6. Display the sum

## Code for find sum of minimum absolute difference of array using python

```a=list(map(int,input("Enter array ").split()))

a.sort()

n=len(a)

if(n%2==1):

me=a[n//2]

else:

me=(a[n//2 -1]+a[n//2] )/2

z=0

for i in a:

z+=abs(i-me)

print("Sum of minimum absolute difference of array is",end=" ")

print(z)```

## Output:

```Enter array 2 3 9 5 6
Sum of minimum absolute difference of array is 10```

## Algorithm 2:

1. Input an array and find the median of the array.

2. Iterate a loop through the array.

3. Subtract the median from each element of the array.

4. Find out the absolute value of the difference.

6. Display the sum

## Python Code:

```import statistics
#Syntax for reading space seperated integers
a=list(map(int,input("Enter array").split()))
#statistics module has method for finding median
me=statistics.median(a)
z=0
for i in a:
z+=abs(a-me)
print("Sum of minimum absolute difference of array is",end="")
print(z)```

## Output:

```Enter array 2 3 9 5 6
Sum of minimum absolute difference of array is 10```