/** * (name header) */ import java.util.Scanner; public class InsertInOrder { pu
ID: 3766708 • Letter: #
Question
/**
* (name header)
*/
import java.util.Scanner;
public class InsertInOrder
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int [] a = new int [5];
int numOfElements = 0;
boolean tryAgain = true;
System.out.print("Number to insert: ");
int numToInsert = input.nextInt();
if (numToInsert != 0)
{
a[0] = numToInsert; // insert first number
++numOfElements; // increment number of elements
// print first number
System.out.print("Array is now: ");
System.out.println(a[0]);
}
while (numOfElements < a.length)
{
System.out.print("Number to insert: ");
numToInsert = input.nextInt();
//Your code here...
// print array
System.out.print("Array is now: ");
for (int i = 0; i < numOfElements; ++i)
{
System.out.print(a[i] + " ");
}
System.out.println();
}
System.out.println(" Array is full.");
}
}
Explanation / Answer
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class InsertInOrder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] a = new int[5];
int numOfElements = 0;
System.out.print("Number to insert: ");
int numToInsert = input.nextInt();
if (numToInsert != 0) {
a[0] = numToInsert; // insert first number
++numOfElements; // increment number of elements
// print first number
System.out.print("Array is now: ");
System.out.print(a[0]);
}
while (numOfElements < a.length) {
System.out.print(" Number to insert: ");
numToInsert = input.nextInt();
// Your code here...
int j;
for (j = 0; j < numOfElements; j++)
// find where it goes
if (a[j] > numToInsert) // (linear search)
break;
for (int k = numOfElements; k > j; k--)
// move bigger ones up
a[k] = a[k - 1];
a[j] = numToInsert; // insert it
numOfElements++; // increment size
System.out.print("Array is now: ");
for (int i = 0; i < numOfElements; ++i) {
System.out.print(a[i] + " ");
}
} // end insert()
// print array
}
}
OUTPUT:
Number to insert: 5
Array is now: 5
Number to insert: 2
Array is now: 2 5
Number to insert: 7
Array is now: 2 5 7
Number to insert: 4
Array is now: 2 4 5 7
Number to insert: 5
Array is now: 2 4 5 5 7
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.