Declare a ArrayList data structure to hold 15 randomly generated integers betwee
ID: 3884688 • Letter: D
Question
Declare a ArrayList data structure to hold 15 randomly generated integers between 1 and 50 (repetition is allowed).
Print the contents of the ArrayList to the screen.
Write a method to sort the ArrayList in Ascending order. The Method will take an ArrayList as a parameter to be sorted. No sorting routine is allowed(i.e. you cannot use Collections.sort. etc.) Call this method in the main method, passing it your original ArrayList
Print the sorted ArrayList to the screen.
Public static void sorting(ArrayList<integer> n) {
//code here
}
Public static void main (String[] args) {
//Call above method here, passing in your ArrayList as a parameter
}
Explanation / Answer
import java.util.*;
public class arrayList{
static void sorting(ArrayList<Integer> a) {
for (int i = 0; i < a.size(); i++) { //to sort the array using bubble sort
for (int j = i+1; j < a.size(); j++) { //in bubble sort we run through the array staring from first position to end if the next value is less than that number we swap the two numbers this has to be done for all the elements of array to sort the array list
if (a.get(i) >a.get(j)) {
int tmp = a.get(i); //swaping two numbers of arraylist
a.set(i,a.get(j));
a.set(j,tmp);
}
}
}
for (int i: a) { //printing arraylist
System.out.print(i + " ");
}
}
public static void main (String[] args) {
ArrayList<Integer> a=new ArrayList<Integer>(); //to create new arraylist
Random rand = new Random(); //to generate random variables
for (int i=0;i<15;i++){ //for loop run for 15 times
int n = rand.nextInt(50) + 1; //to generate random integers between 1 to 50
a.add(n); //to add it to list
}
System.out.println(a.toString()); //to print the array list
sorting(a); //calling sorting function
}
}
output:
[47, 30, 18, 6, 22, 35, 33, 42, 46, 9, 33, 32, 47, 41, 5]
5 6 9 18 22 30 32 33 33 35 41 42 46 47 47
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.