Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to find the median of an Integer array in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MedianOfIntArray_Java {
    private static double find_median_of_int_array(ArrayList<Integer> al) {
    	Collections.sort(al);
    
    	for (int num : al) {
    		System.out.print(num);
    		System.out.print(" ");
    	}
    
    	double median;
    	int size = al.size();
    
    	if (size % 2 == 0) {
    		median = (al.get(size / 2 - 1) + al.get(size / 2)) / 2.0;
    	}
    	else {
    		median = al.get(size / 2);
    	}
    
    	return median;
    }
    public static void main(String[] args) {
        ArrayList<Integer> al = new ArrayList<Integer>(Arrays.asList(40, 70, 60, 55, 90, 45, 100, 80, 65, 50, 82, 58));

    	//  ArrayList<Integer> al = {24, 25, 26, 27, 28, 30, 32, 51, 34, 35, 36, 40, 60, 42, 49};
    	//  24 25 26 27 28 30 32 34 35 36 40 42 49 51 60
    	//  median = 34.00
    
    	double median = find_median_of_int_array(al);
    
    	System.out.println("\nmedian = " + median);
    }
}



/*
run:
   
40 45 50 55 58 60 65 70 80 82 90 100 
median = 62.5  
   
*/

 



answered Jul 17, 2024 by avibootz
edited Jul 18, 2024 by avibootz

Related questions

1 answer 61 views
3 answers 167 views
1 answer 77 views
77 views asked Jul 17, 2024 by avibootz
1 answer 89 views
1 answer 71 views
1 answer 93 views
1 answer 102 views
...