In: Computer Science
Written in JAVA Code
Write a program that inserts 25 random integers from 0 to 100 in order into a LinkedList object. The program should sort the elements, then calculate the sum of the elements and the floating-point average of the elements.
import java.util.LinkedList; import java.util.Random; public class LinkedListSortSumAvg { public static void sort(LinkedList<Integer> list){ int i,j; int temp; for(i = 0;i<list.size();i++){ for(j = i+1;j<list.size();j++){ if(list.get(i).compareTo(list.get(j))>0){ temp = list.get(i); list.set(i,list.get(j)); list.set(j,temp); } } } } public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<>(); Random random = new Random(); // Generating 25 random numbers for(int i= 0;i<25;i++){ list.add(random.nextInt(100)); } // Sorting list sort(list); System.out.println(list); // Calculating sum int sum = 0; for(int i = 0;i<list.size();i++){ sum += list.get(i); } System.out.println("Sum = "+sum); // Calculating average float avg = (float) (1.0*sum/list.size()); System.out.println("Average = "+avg); } }