Java Program to Sort Array Alternatively Based on Highest Average of Even or Odd Elements of the Array

In the previous article, we have seen Java Program to Print the Array Element Address When the Base Address and Array Element Size is Given

In this article we will see how to sort array alternatively based on highest average of even or odd elements of the array.

Java Program to Sort Array Alternatively Based on Highest Average of Even or Odd Elements of the Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Explanation:

Given an array consisting of even and odd elements. The task is to calculate the average of even elements of the array and also to calculate the average of the odd elements of the array.

Then we have to sort them accordingly depending upon the condition

  • If the average of even elements is greater than the average of odd elements then sort the array in ascending order.
  • If the average of odd elements is greater than the average of even elements then sort the array in descending order.

Example 1 :

Input : arr[ ] = {6, 11, 2, 5, 4, 7, 10,3}

Output : {11, 10, 7, 6, 5, 4, 3, 2}

Explanation : The average of odd elements (6.5) is greater than the average of even elements (5.5) so the array is sorted in descending order.

Example 2 :

Input : arr[ ] = {9, 14, 3, 8, 12, 7, 11}

Output : {3, 7, 8, 9, 11, 12, 14}

Explanation : The average of even elements (11.3) is greater than the average of odd elements (7.5) so the array is sorted in ascending order.

Approach:

  • Check each elements of the array it is even or odd.
  • even element add to Even_Sum and odd element add to Odd_Sum.
  • Keep track on total number of even elements and Odd elements as total number of even elements or odd elements is required during average calculation.
  • Find the average of even elements and odd elements.
  • Compare the average of both even elements and odd elements.
  • If the average of even elements is greater than the average of odd elements then sort the array in ascending order.
  • If the average of odd elements is greater than the average of even elements then sort the array in descending order.

Program:

import java.io.*; 
  
class Main 
{ 
    public static float even_count = 0;  
    public static float even_sum=0; 
    public static float odd_sum=0;
    public static float odd_count = 0;  
    public static float even_avg;
    public static float odd_avg;
  
    static void result(int arr[], int arr_size) 
    { 
        // loop to read all the values in 
        // the array 
        for(int i = 0 ; i < arr_size ; i++)  
        { 
          	// checks odd number
            if ((arr[i] & 1) == 1)
            {
                odd_count ++ ; 
                odd_sum=odd_sum+arr[i];
            }
          	// checks even number
            else   
            {
                even_count ++ ;  
                even_sum=even_sum+arr[i];
            }
        }
        System.out.println("Sum of odd numbers: "+odd_sum);
        System.out.println("Sum of even numbers: "+even_sum);
        
    }
  	// average function to calculate the average 
  	// of even numbers and odd numbers
    static void average(float e_avg, float o_avg) 
    {
        // average of even numbers in the array
        even_avg=even_sum/even_count; 
      	// average of odd numbers in the array
        odd_avg=odd_sum/odd_count;  
        
        System.out.println("Average of odd numbers: "+odd_avg);
        System.out.println("Average of even numbers: "+even_avg);
    }

  	// compare method to calculate the which average is greater
    static void compare(int arr[], float eavg, float oavg, int n) 
    {
        int temp;
      	// If average of even elements is 
     	// greater then ascending order sort
        if(eavg>oavg) 
        {
            System.out.println("Average of even elements are greater than average of odd elements.So ASCENDING ORDER");
          	// sorting the array in ascending order
             for (int i = 0; i < n; i++) 
            {
                for (int j = i + 1; j < n; j++) 
                {
                if (arr[i] > arr[j]) 
                    {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    }
                }
            }
          	// printing the sorted array
            System.out.println("Ascending Order :");
            for (int i = 0; i < n; i++) 
            {
                System.out.println(arr[i]);
            }
        }
      // If average of odd elements is 
      // greater then descending order sort
        else
        {
            System.out.println("Average of odd elements are greater than average of even elements.So DESCENDING ORDER");
 			// sorting the array in descending order
            for (int i = 0; i < n; i++) 
            {
            for (int j = i + 1; j < n; j++) 
                {
                 if (arr[i] < arr[j]) 
                    {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    }
                }
            }
          	// printing the sorted array
            System.out.println("Descending Order :");
            for (int i = 0; i < n; i++) 
            {
                System.out.println(arr[i]);
            }
        }
    }
    // Driver Code 
    public static void main (String[] args)  
    {     
        int arr[] = {9, 14, 3, 8, 12, 7, 11}; 
        int n = arr.length; 
        result(arr, n); 
        average(even_sum,odd_sum);
        compare(arr,even_avg,odd_avg,n);
    } 
}

Output:

Sum of odd numbers: 30.0
Sum of even numbers: 34.0
Average of odd numbers: 7.5
Average of even numbers: 11.333333
Average of even elements are greater than average of odd elements.So ASCENDING ORDER
Ascending Order :
3
7
8
9
11
12
14

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Related Java Programs: