A class InsSort contains an array of integers which sorts the elements in a particular order.
Some of the members of the class are given below:
Class name: InsSort
Data members/instance variables:
arr[]: stores the array elements
size: stores the number of elements in the array
Methods/Member functions:
InsSort(int s): constructor to initialize size = s
void getArray(): accepts the array elements
void insertionSort(): sorts the elements of the array in descending order using the Insertion Sort technique
double find(): calculates and returns the average of all the odd numbers in the array
void display(): displays the elements of the array in a sorted order along with the average of all the odd numbers in the array by invoking the function find() with an appropriate message
Specify the class InsSort giving details of the constructor(), void getArray(), void insertionSort(), double find() and void display(). Define a main() function to create an object and call all the functions accordingly to enable the task.
import java.util.Scanner;
class InsSort{
int arr[];
int size;
public InsSort(int s){
size = s;
arr = new int[size];
}
public void getArray(){
Scanner in = new Scanner(System.in);
System.out.println("Enter array elements:");
for(int i = 0; i < size; i++)
arr[i] = Integer.parseInt(in.nextLine());
}
public void insertionSort(){
for(int i = 1; i < size; i++){
int key = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] < key){
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public double find(){
int count = 0;
int sum = 0;
for(int i = 0; i < size; i++){
if(arr[i] % 2 != 0){
sum += arr[i];
count++;
}
}
return (double)sum / count;
}
public void display(){
System.out.print("Sorted list: ");
for(int i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("\nAverage of odd numbers: " + find());
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Array size: ");
int s = Integer.parseInt(in.nextLine());
InsSort obj = new InsSort(s);
obj.getArray();
obj.insertionSort();
obj.display();
}
}