Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Declare a ArrayList data structure to hold 15 randomly generated integers betwee

ID: 3884685 • 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

Below is your code: -

ArrayListSorter.java

import java.util.ArrayList;

import java.util.Random;

public class ArrayListSorter {

public static void main(String[] args) {

Random r = new Random();

ArrayList<Integer> list = new ArrayList<>();

for (int i = 0; i < 15; i++) {

list.add(r.nextInt(50) + 1);

}

System.out.print("List before sorting : ");

for (int i = 0; i < list.size(); i++) {

System.out.print(list.get(i) + " ");

}

sorting(list);

System.out.println();

System.out.print("List after sorting : ");

for (int i = 0; i < list.size(); i++) {

System.out.print(list.get(i) + " ");

}

}

// method to sort the list

public static void sorting(ArrayList<Integer> n) {

for (int i = 0; i < n.size(); i++) {

for (int j = n.size() - 1; j > i; j--) {

if (n.get(i) > n.get(j)) {

int tmp = n.get(i);

n.set(i, n.get(j));

n.set(j, tmp);

}

}

}

}

}

Sample Run

List before sorting : 10 43 46 42 36 27 26 1 4 8 28 35 13 29 32
List after sorting : 1 4 8 10 13 26 27 28 29 32 35 36 42 43 46

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote