Как найти медиану массива java

Sorting the array is unnecessary and inefficient. There’s a variation of the QuickSort (QuickSelect) algorithm which has an average run time of O(n); if you sort first, you’re down to O(n log n). It actually finds the nth smallest item in a list; for a median, you just use n = half the list length. Let’s call it quickNth (list, n).

The concept is that to find the nth smallest, choose a ‘pivot’ value. (Exactly how you choose it isn’t critical; if you know the data will be thoroughly random, you can take the first item on the list.)

Split the original list into three smaller lists:

  • One with values smaller than the pivot.
  • One with values equal to the pivot.
  • And one with values greater than the pivot.

You then have three cases:

  1. The “smaller” list has >= n items. In that case, you know that the nth smallest is in that list. Return quickNth(smaller, n).
  2. The smaller list has < n items, but the sum of the lengths of the smaller and equal lists have >= n items. In this case, the nth is equal to any item in the “equal” list; you’re done.
  3. n is greater than the sum of the lengths of the smaller and equal lists. In that case, you can essentially skip over those two, and adjust n accordingly. Return quickNth(greater, n – length(smaller) – length(equal)).

Done.

If you’re not sure that the data is thoroughly random, you need to be more sophisticated about choosing the pivot. Taking the median of the first value in the list, the last value in the list, and the one midway between the two works pretty well.

If you’re very unlucky with your choice of pivots, and you always choose the smallest or highest value as your pivot, this takes O(n^2) time; that’s bad. But, it’s also very unlikely if you choose your pivot with a decent algorithm.

Sample code:

import java.util.*;

public class Utility {
   /****************
   * @param coll an ArrayList of Comparable objects
   * @return the median of coll
   *****************/
   
   public static <T extends Number> double median(ArrayList<T> coll, Comparator<T> comp) {
      double result;
      int n = coll.size()/2;
      
      if (coll.size() % 2 == 0)  // even number of items; find the middle two and average them
         result = (nth(coll, n-1, comp).doubleValue() + nth(coll, n, comp).doubleValue()) / 2.0;
      else                      // odd number of items; return the one in the middle
         result = nth(coll, n, comp).doubleValue();
         
      return result;
   } // median(coll)
   
   

   /*****************
   * @param coll a collection of Comparable objects
   * @param n  the position of the desired object, using the ordering defined on the list elements
   * @return the nth smallest object
   *******************/
   
   public static <T> T nth(ArrayList<T> coll, int n, Comparator<T> comp) {
      T result, pivot;
      ArrayList<T> underPivot = new ArrayList<>(), overPivot = new ArrayList<>(), equalPivot = new ArrayList<>();
      
      // choosing a pivot is a whole topic in itself.
      // this implementation uses the simple strategy of grabbing something from the middle of the ArrayList.
      
      pivot = coll.get(n/2);
      
      // split coll into 3 lists based on comparison with the pivot
      
      for (T obj : coll) {
         int order = comp.compare(obj, pivot);
         
         if (order < 0)        // obj < pivot
            underPivot.add(obj);
         else if (order > 0)   // obj > pivot
            overPivot.add(obj);
         else                  // obj = pivot
            equalPivot.add(obj);
      } // for each obj in coll
      
      // recurse on the appropriate list
      
      if (n < underPivot.size())
         result = nth(underPivot, n, comp);
      else if (n < underPivot.size() + equalPivot.size()) // equal to pivot; just return it
         result = pivot;
      else  // everything in underPivot and equalPivot is too small.  Adjust n accordingly in the recursion.
         result = nth(overPivot, n - underPivot.size() - equalPivot.size(), comp);
         
      return result;
   } // nth(coll, n)
   
   
   
   public static void main (String[] args) {
      Comparator<Integer> comp = Comparator.naturalOrder();
      Random rnd = new Random();
      
      for (int size = 1; size <= 10; size++) {
         ArrayList<Integer> coll = new ArrayList<>(size);
         for (int i = 0; i < size; i++)
            coll.add(rnd.nextInt(100));
      
         System.out.println("Median of " + coll.toString() + " is " + median(coll, comp));
      } // for a range of possible input sizes
   } // main(args)
} // Utility

Java code To Calculate Median – In this article, we will brief in on the mentioned means to  Finding the middle element in array. The following median code has been written in 4 different ways. If you have any doubts you can leave a comment here.

The source code has written in:

  • Using Standard Method
  • Using Static Method
  • Using Scanner Class
  • Using Command Line Arguments
  • Using Separate Class

The median of a given group of data is the value which falls in between of the given values. The only difference between Median and Mean is that Mean gives a rough average of the whole data.

Whereas the median will give the exact value which falls in between of the smallest and highest values.

java middle element array

As you can see, in the given order of values, firstly, it has to be arranged in an ascending or descending order. Then, the middle value is noted down.

9 is the middle value of the given set of numbers. Thus, 9 is the median of the group.

Calculate Median Array – Standard Method

For this problem, we first taken the inputs. The inputs are the number of elements or the size of array and the data values which are to be stored in the array (a).

One important thing to be kept in mind is that the data values are to be entered in a sorted order. This is necessary because we need to find the middle element.

After taking the inputs, we need to first check whether the number of elements is odd or even.

  • if(n%2==1)
  • If the number of elements is odd then, the center-most element is the median.
  • m=a[(n+1)/2-1];
  • Else, the average of the two middle elements.
  • m=(a[n/2-1]+a[n/2])/2;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

class Median

{

public static void main(String arg[])

{

                 int n=5;

   double a[]=new double[n];

                   a[0]=10;

    a[1]=20;

    a[2]=30;

    a[3]=40;

    a[4]=50;

double m=0;

if(n%2==1)

{

m=a[(n+1)/21];

}

else

{

m=(a[n/21]+a[n/2])/2;

}

       System.out.println(“Median :”+m);

}

}

Output:

Using Static Method

In the case of making use of static method, we split up the code into two parts.

The inputs i.e., the size of array and data values of array in a sorted order, is read using the scanner class.

After reading the inputs, another static method is called to which the inputs are passed as arguments.

This method consists of set of statements to return the mean based on the same logic as discussed above. T

In this, both the main method as well as the static method are written within the same class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

import java.util.Scanner;

class Median

{

   public static void main(String args[])

    {

Scanner sc=new Scanner(System.in);

System.out.println(“enter a number”);

int a=sc.nextInt();

double[] input=new double[a];

System.out.println(“enter “+a+” elements”);

for(int i=0;i<a;i++)

{

input[i]=sc.nextDouble();

}

double res=medianCal(a,input);

System.out.println(“Median :”+res);  

    }

static double medianCal(int  n,double in[])

{

double m=0;

if(n%2==1)

{

m=in[((n+1)/2)1];

}

else

{

m=(in[n/21]+in[n/2])/2;

}

return m;

}

}

Output1:

enter a number

4

enter 4 elements

1

2

3

4

Median :2.5

Using Scanner Class

In the above example, we had mentioned that, the inputs are taken making use of the scanner class.

Scanner class in Java is that class which reads input at runtime given by the tester/user for any primitive datatype.

So here, we make use of the scanner class to first read an integer number which is considered as the size of array (total number of data values) followed by which we take the data values which could either be integers or decimal value and therefore, we choose double type. It is essential to make sure that, these data values must be taken in sorted order only.

After gathering the inputs, we will find the median of the given data values with the same logic as explained above.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import java.util.Scanner;

class Median

{

   public static void main(String args[])

    {

Scanner sc=new Scanner(System.in);

System.out.println(“enter a number”);

int n=sc.nextInt();

double[] input=new double[n];

System.out.println(“enter “+n+” elements”);

double m=0;

for(int i=0;i<n;i++)

{

input[i]=sc.nextDouble();

}

if(n%2==1)

{

m=input[(n+1)/21];

}

else

{

m=(input[n/21]+input[n/2])/2;

}

       System.out.println(“Median :”+m);  

   }

}

Output:

enter a number

5

enter 5 elements

1

2

3

4

5

Median :3.0

Using Command Line Arguments

Apart from making use of scanner class to take inputs at runtime, we can also give values along with the run command itself separated by space between each argument.

This method is called the using of command line arguments.

Here, we first give the number of elements (arg[0]) followed by which we give as many arguments having data values as mentioned. These variables are first converted to their respective datatypes using parsing and then stored in the variable.

After acquiring all the inputs the same steps as mentioned in the beginning are followed.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

class Median

{

   public static void main(String args[])

    {

int n=Integer.parseInt(args[0]);

double[] input=new double[n];

double m=0;

for(int i=0;i<n;i++)

{

input[i]=Double.parseDouble(args[i+1]);

}

if(n%2==1)

{

m=input[(n+1)/21];

}

else

{

m=(input[n/21]+input[n/2])/2;

}

       System.out.println(“Median :”+m);  

   }

}

Using Separate Class

To enhance the readability and make things smoother to find any part of the code if we ever require to make modifications in the future, we split the code into different classes.

Here, the class containing main method has all the necessary input operations using the scanner class. This is followed by creating of an object referencing another class (MedianCal).

This separate class (MedianCal) has a constructor which is responsible for performing set of instructions as mentioned above to find the median and store it in a variable of the separate class (MedianCal).

This variable is called in the main method with the help of the object created and printed as output.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

import java.util.Scanner;

class MedianCal

{

double m=0;

MedianCal(int  n,double in[])

{

if(n%2==1)

  {

m=in[((n+1)/2)1];

  }

else

   {

m=(in[n/21]+in[n/2])/2;

  }

}

}

class Median

{

   public static void main(String args[])

    {

Scanner sc=new Scanner(System.in);

System.out.println(“enter a number”);

int a=sc.nextInt();

double[] input=new double[a];

System.out.println(“enter “+a+” elements”);

for(int i=0;i<a;i++)

{

input[i]=sc.nextDouble();

}

MedianCal res=new MedianCal(a,input);

System.out.println(“Median :”+res.m);  

    }

}

Output:

enter a number

5

enter 5 elements

1

2.5

3

3.5

4

Median :3.0

In the code you’ve provided it looks like you’re trying to find the mean not the median. I’ve provided some code below that should help with finding the mean. To find the median you’d need to sort the array, which is a little more complicated.

The short answer is to remove the input=0 line. Assuming that data is a public variable and that sum is a function that sums that public variable your code should work.

The implementation should depend on the context, but I would recommend a static function that takes an array of doubles as the single argument.

public class Median{
   public static void main(String[] args){
      double numbers[] ={1.0, 2.0, 3.0};
      System.out.println(median(numbers));
   }
   public static double median(double[]x){
      double sum = 0;
      for(int i=0;i<x.length;i++){
         sum += x[i];
      }
      return sum/x.length;
   }
}

Java – Find median of unsorted array

In this article, we will take a look at 2 different ways to find median of elements of an array with programs and their explanation.
Before diving into the solution, it is better to know the meaning of median of array values.
What is Median ?
Median of a sequence(or an array) of numbers is the middle element of the sequence when the total number of elements is odd or the average of middle elements when the total number of elements is even, provided the sequence is sorted.
Example,

When total elements are odd

Consider the sequence: 2, 3, 6, 12, 15, 34, 65, 78, 99
Total number of elements:     9(odd)
Median will be 5th element: 15

When total elements are even

Consider the sequence: 2, 3, 6, 12, 15, 34, 65, 78
Total number of elements:     8(even)
Median will be average of 5th element: (12 + 15)/2 = 13.5

Thus,

If n is odd then Median (M) = value of ((n + 1)/2)th item term.
If n is even then Median (M) = value of [((n)/2)th item term + ((n)/2 + 1)th item term ]/2

where,
n is the total number of elements in the sequence or array.

How to calculate Median in java
Following are the different ways in which you can calculate median in a java program.

Method 1 : Finding the middle element
Program is given below

public class MedianFinder {
   public static void main(String[] args) {
     // initialize array with odd number of element
     int[] values = { 2, 3, 6, 12, 15, 34, 65, 78, 99 };
     // calculate median
     double median = median(values);
     System.out.println("Median is : " + median);
     // re-initialize array with even number of element
     values = { 2, 3, 6, 12, 15, 34, 65, 78};
     // calculate median
     median = median(values);
     System.out.println("Median is : " + median);
  }

  static double median(int[] values) {
     // sort array
     Arrays.sort(values);
     double median;
     // get count of scores
     int totalElements = values.length;
     // check if total number of scores is even
     if (totalElements % 2 == 0) {
        int sumOfMiddleElements = values[totalElements / 2] +
                                  values[totalElements / 2 - 1];
        // calculate average of middle elements
        median = ((double) sumOfMiddleElements) / 2;
     } else {
        // get the middle element
        median = (double) values[values.length / 2];
  }
  return median;
 }
}

Above program initializes arrays with an odd number of elements and even number of elements and passes these arrays to a method which calculates median.
This method firsts sorts the array using sort() method of java.util.Arrays class.

After this, it checks if the total number of elements of array is even or odd by taking modulus of total elements with 2 and comparing the remainder with 0.
If the remainder is 0, the number of elements are even else they are odd.

1. If the total elements are odd
,
it retrieves the middle element by dividing the total number of elements by 2.
2. If the total elements are even,
it calculates the sum of middle two elements(12 and 15) and divides this sum by 2 to calculate the average of middle elements.

Output

Median is : 15
Median is : 13.5

Method 2 : Using Apache Math Library
Apache Math library provides many utility classes and methods to calculate mathematical entities and solution to programming problems such as mean, median, matrix operations, complex numbers, probability distribution and many more.

This library has a class Median in package org.apache.commons.math3.stat.descriptive.rank.
Median has a median method which takes an array and returns the median value from these array elements.

median method takes a double array as argument. Thus if you have an integer array, then you need to convert it to an array of double elements.

Usage of this library to calculate median is shown below

public class MedianFinder {
    public static void main(String[] args) {
      // initialize array
      double[] values = { 1.2, 3, 4, 5, 8 };
      // calculate median
      double median = median(values);
      System.out.println("Median is : " + median);
    }

    static double median(double[] values) {
      // create an object of Median class
      Median median = new Median();
      // calculate median
      double evaluate = median.evaluate(values);
      return median;
    }
}

Output

Median is : 4.0

Note that now no sorting of array is required and you do not need to check the length of the array and provide different handling as per the total elements being odd or even, the library handles this stuff itself.

Apache commons library can be found at this link.

Click the clap below if the post was helpful.

How to Calculate median in Java? | With Array and List | Programming Blog

Find median of Java Array and List values using 2 ways

Find median of Java Array and List values using 2 ways

What is Median?

Median is mid value of particular data set. This data set must be sorted. 

In simple word, Median is mid value of sorted data.

Median will be middle, if total number of elements is odd or average of middle elements when total number of elements is even.

Example :

When total number of elements are odd

1, 2, 3, 4, 5, 6, 7
Median will be : 4

2, 3, 5, 7, 8
Median will be : 5

When total number of elements are even

1, 2, 3, 4
Median will be : (2+3) / 2 : 2.5

2, 4, 6, 8, 10, 20, 25, 30
Median will be : (8+10) / 2 : 9

So the formula become for our code :

For odd elements :

Median = (Total length / 2)

For even elements :

Median = (Total length / 2) + (Total length / 2 – 1) / 2

So lets jump on code. We will take elements form user.

Method 1 : Using code logic

In this approach, we does not use any library function for find median.

Example 1 : Find median from Java array

import java.util.Arrays;
import java.util.Scanner;

public class FindTheMedian {

    public static void main(String[] args) {

                Scanner sc = new Scanner(System.in);
        System.out.println(“Enter total elements length”);
        int length = sc.nextInt();
        int[] array = new int[length];
        System.out.println(“Enter elements”);
        for (int i = 0; i < length; i++) {
            array[i] = sc.nextInt();
        }

                // Sort the Array
        Arrays.sort(array);
        double median = 0;

                // When total length is Even
        if (length % 2 == 0) {
            median = ((double) array[length/2] + (double) array[(length/2) – 1]) / 2;

                // When total length is Odd
        } else {
            median = (double) array[length/2];
        }

                System.out.println(“Median is : “+median);
    }
}

Output :

Enter total elements length
6
Enter elements
2 4 6 8 10 15
Median is : 7.0

Enter total elements length
5
Enter elements
1 2 3 4 5
Median is : 3.0

Example 2 : Find median from Java List

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class FindTheMedian {

    public static void main(String[] args) {

                Scanner sc = new Scanner(System.in);
        System.out.println(“Enter total elements length”);
        int length = sc.nextInt();

                System.out.println(“Enter elements”);
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            list.add(sc.nextInt());
        }

                // Sort the List
        Collections.sort(list);
        double median = 0;

                // When total length is Even
        if (length % 2 == 0) {
            median = ((double)list.get(length/2) + (double)list.get((length/2)-1)) / 2;
        }

                // When total length is Odd
        else {
            median = (double)list.get(length/2);
        }

        System.out.println(“Median is : “+median);
    }
}

Output :

Enter total elements length
8
Enter elements
5 1 6 8 10 0 2 7
Median is : 5.5

Enter total elements length
5
Enter elements
90 10 8 50 15
Median is : 15.0

Method 2 : Using Apache commons library

This problem can also solve by Apache commons Math library. 

org.apache.commons.math3.stat.descriptive.rank.Median package provides solution for evaluate median of array.

We must have to use double array for use this library. lets see how ii works.

import java.util.Scanner;

import org.apache.commons.math3.stat.descriptive.rank.Median;

public class FindTheMedian {

    public static void main(String[] args) {

                Scanner sc = new Scanner(System.in);
        System.out.println(“Enter total elements length”);
        int length = sc.nextInt();
        double[] array = new double[length];

                System.out.println(“Enter elements”);
        for (int i = 0; i < length; i++) {
            array[i] = sc.nextDouble();
        }

                Median median = new Median();
        double answer = median.evaluate(array);
        System.out.println(answer);
    }
}

Output :

Enter total elements length
6
Enter elements
10 15 8 4 9 7
8.5

Enter total elements length
5
Enter elements
9 7 2 5 1
5.0

Other articles :

  • Java program to check given alphabet is an uppercase or lowercase vowel or not  
  • Sort custom object property with null values using Java 8 lambda expression
  • Divide and compute Modulo of large number | Print modulo of BigInteger in Java | Convert large String to BigInteger in Java 

Добавить комментарий