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 C Program to find sum of minimum absolute difference of the given array

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
sum of minimum absolute difference

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.
sum of minimum absolute difference in C

Sum of minimum absolute difference in C

#include <stdio.h>

void sort(int arr[],int n){
int temp=0;
for(int i=0;i<n;i++){

for(int j=0;j<n;j++){

if(arr[i]<arr[j]){

temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;

}

}
}
}

int main()
{
int n;
printf("Enter the size of the array :");
scanf("%d",&n);

int arr[n];

printf("\nEnter the elements of array :");
for(int i=0; i<n;i++)
scanf("%d",&arr[i]);

sort(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++){

int x=arr[i]-median;
if(x<0)
sum += -x;

else sum += x;
}
printf("Minimum Absolute Difference Sum is %d", sum);
return 0;
}
Output :

Enter the size of the array : 4

Enter the elements of array : 2 4 5 3

Minimum Absolute Difference Sum is 4