JAVA!! *Write a program that sorts a range of integers typed into the console us
ID: 3937429 • Letter: J
Question
JAVA!!
*Write a program that sorts a range of integers typed into the console using the counting sort algorithm2.
*Values typed that are not in the range 1-100 (inclusive) should be ignored.
*You must prompt the user to enter the numbers.
*Then, print out the numbers entered in sorted order (on a single line, with spaces between subsequent values).
*the hasNextInt() method of the scanner will be useful, and when testing in Eclipse, press enter and then, once on the empty line, press CTRL-D (Mac) or CTRL+Z (Windows) when you are done typing numbers.
*You must use an array to keep track of how many times each number has been seen. The array should have 100 elements (one for each number).
*Index 0 should be used to track the number of 1’s, index 1 to track the 2’s, index 2 to track the 3’s, etc., up to index 99 for the 100’s.
*think about how to convert each number you read into the correct index and then increment that value in the array.
(Here is an example run of the program:)
Enter numbers from 1-100: 1 9 2 100 99 98 90 10
1 2 9 10 90 98 99 100
Explanation / Answer
import java.util.*;
public class Sort
{
public static void main(String args[])
{
System.out.print("Enter numbers from 1-100: ");
Scanner sc = new Scanner (System.in);
int arr[] = new int[100];
int len = 0, c, rem;
while (sc.hasNextInt() == true )
{
int n = sc.nextInt(); //Accept a number
//Validates the entered number must be greater than equal to 1 to 100
if(n >= 1 && n <= 100)
{
//Checks for the single digit
if(n < 10)
{
rem = n % 10; //Finds the remainder
arr[rem] = n; //At the remainder position store the inputed number
}
else if(n < 100) //Checks for the double digit
{
rem = n % 100; //Finds the remainder
arr[rem] = n; //At the remainder position store the inputed number
}
else
arr[99] = n;
}
}
//Displays the data in sorted order
for(c = 0; c < 100; c++)
{
if(arr[c] != 0)
System.out.println(" " + arr[c]);
}
}
}
Output:
Enter numbers from 1-100: 23
56
99
100
102
59
89
91
^Z
23
56
59
89
91
100
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.