# C++ Program to find sum of minimum absolute difference of the given array

## Sum of minimum absolute difference in C++

Here, in this page we will discuss sum with minimum absolute difference in C++.

To find minimum absolute difference of array 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

• 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]
• Using statistics module
Check the image how to find median using first method
Example : 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 :

• Take the size of the array from the user and store it in variable say n.
• Declare an array of size n.
• Take n integers from the user and store them in array.
• Sort the array in increasing order.
• Create a variable say median that store the median of the array in it.
• If the size of array is even then median= (a[n/2]+a[n/2+1])/2, otherwise median = a[n/2], here a [] is the array and n is the size of the array.
• Create a variable say sum that holds the sum in it and initialize it with 0.
• Iterate over the array and add the absolute difference in the sum.
• Print the sum. ## C++ Program to find sum of minimum absolute difference of the given array

`#include <bits/stdc++.h>using namespace std;int main(){    int n;    cout<<"Enter the size of the array :";    cin>>n;        int arr[n];        cout<<"\nEnter the elements of array :";    for(int i=0; i<n;i++)    cin>>arr[i];         sort(arr, arr+n);  //sort first array        int median ; //variable to store the median        if(n%2==0)    median = ((arr[n/2]+arr[n/2+1])/2);        else median = arr[n/2];        int sum =0 ; // variable to hold the sum        for(int i=0; i<n; i++){     sum += abs(arr[i]-median);    }        cout<<"Minimum Absolute Difference Sum is "<<sum;    return 0;}`
`Output :Enter the size of the array : 4Enter the element of array : 2 4 5 3Minimum Absolute Difference Sum is 4`