Find the median in my array while also sorting the numbers from smallest to largest

Viewed 1008

This is what I've done so far; I was able to calculate the average, but I'm not sure how to find the median. I also know that I need to sort the array to make it easier.

 public class SAA {
     public static void main(String[] args) {
         int[] num = {60, 70, 82, 1216, 57, 82, 34, 560, 91, 86};
         int total = 0;
         for (int i = 0; i < num.length; i++) {
             if ((num[i] > 0) && (num[i] < 100)) {
                 total += num[i];
             }
         }
         System.out.println(total / 10);
     }
 }

This is my attempt at using bubble sort:

public class Bubblesort {
    public static void main(String[] args) {
        int[] num = {60, 70, 82, 1216, 57, 82, 34, 560, 91, 86};
        int temp = 0;
        int[] add = new int[num.length + 1];
        for (int i = 0; i < num.length; i++) {
            for (int j = i + 1; j < num.length; j++) {
                if (num[i] > num[j]) {
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
        for (int i = 0; i < num.length; i++) {
            System.out.print(num[i] + " ");
        }
    }
}
2 Answers

Median is the middle element of the sorted array if the array size is odd, else it is the average of the middle two elements. The following code snippet finds the median of the array.

public static void main(String[] args) {
        int[]num = {60, 70, 82, 1216, 57, 82, 34, 560, 91, 86};
        int median;
        int len = num.length;
        
        Arrays.sort(num); // sorts the array
        
        //check if the length is odd
        if(len%2 != 0)
            median = num[len/2];
        else // length is even
            median = (num[(len - 1) / 2] + num[len / 2])/2;
        System.out.println(median);
    }
        int min = 0; 
        int max = 0; 
        
        for (int i = 0; i < numbers.length; i++)
        {
            for (int j = 0; j < numbers.length-1; j++)
            {
                min = Math.min(numbers[j], numbers[j+1]); //using min and max methods
                max = Math.max(numbers[j], numbers[j+1]); 
                numbers[j] = min; //placing the smaller value on the left
                numbers[j+1] = max; //placing the larger value on the right
            }
        }

This is the program to bubble sort an array in a short and simpler way, you should use this along with @Sr_33's answer as well!

Related