Create an ArrayList data structure that will hold Integer values. Prompt the use
ID: 3670082 • Letter: C
Question
Create an ArrayList data structure that will hold Integer values.
Prompt the user for a number that is greater than 50 which will be the number of items you will place into this ArrayList data structure you created.
Generate this amount of random number (the random numbers should range from 1 to 100) one at a time and insert this number (one at a time) into the ArrayList.
These numbers are to be inserted in sequential order (i.e. from smallest to largest). For example if you already have 3 numbers in the list as in 3, 6, 8 and your next randomly generated number is 5, your new list must be 3, 5, 6, 8 before you even generate another random number, and so on and so on.
After you are finished, display the entire content of the ArrayList on the screen.
Remember --- DO NOT GENERATE ALL THE NUMBERS BEFORE STARTING TO INSERT INTO THE LIST AND DO NOT USE ANY SORTING ROUTINE FROM THE LIBRARY TO SORT THE ArrayList
Explanation / Answer
import java.io.*;
import java.util.*;
class InsertSort
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList list = new ArrayList();
System.out.print("Enter the number of elements to insert: ");
int numOfElements = sc.nextInt();
System.out.print("Enter the elements to insert: ");
for(int i = 0; i < numOfElements; i++)
{
int x = sc.nextInt();
list.ensureCapacity(i+1);
int k;
for(k = list.size(); k > 0; k--)
if((int)list.get(k-1) > x)
list.add(k, list.get(k-1));
else
break;
list.add(k, x);
}
for(int i = 0; i < numOfElements; i++)
{
System.out.print(list.get(i)+" ");
if(i % 10 == 0)
System.out.println();
}
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.