In: Computer Science
Write a Java program to create an array of a specific size (which is an input from the user) and fill it with random numbers between 1 and 100. Then sort the array and count how many of these numbers are originally at sorted position. Display that original array, the sorted array, and the count (number of elements originally at sorted position). |
|
Program:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Scanner declaration
Random rand = new Random();
int size,temp,count=0; // variable declaration
System.out.print("\nEnter the size of the random array: ");
size = sc.nextInt(); // Accept size of the random array
int[] array = new int[size]; // declare array
int[] originalArray = new int[size]; // declare array
for (int i = 0; i < size; i++) { // Loop to assign random numbers
array[i] = rand.nextInt(100)+1;
originalArray[i]=array[i];
}
/* Loop to sort array elements*/
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < size; i++) // Loop to count number of elements in its original positions
{
if(originalArray[i]==array[i]) // if it is at same position
count++; // increment count
}
System.out.println("\n\nThe original array elements:\n");
for (int i = 0; i < size; i++) // Loop to print original array
{
System.out.print(originalArray[i]+" "); // print original array
}
System.out.println("\n\n\nThe sorted array elements:\n");
for (int i = 0; i < size; i++) // Loop to print sorted array
{
System.out.print(array[i]+" "); // print sorted array
}
System.out.println("\n\n\nNumber of elements originally at sorted position: "+count); // print cout of number of elements originally at sorted position
}
}
Output: