Write a java program that reads in 20 numbers and stores them into an array of t
ID: 3582299 • Letter: W
Question
Write a java program that reads in 20 numbers and stores them into an array of type integer with a max size of 50. You should use a method to read the numbers. Use the following 20 numbers to test your program (213 1 24 9 -5 432 32 95 120 210 421 529 23 42 94 16 21 -7 234 20). Write a method that performs a selection sort of the list. Write a method that performs a search for the sorted array. Sort and display the array. Write a method that searches the array for a number entered by the user and returns whether it was found or not and the location of that number in the array (position).
Explanation / Answer
import java.util.*;
public class HelloWorld{
/* method to read element of the array */
public static void read(int[] arr){
Scanner input=new Scanner(System.in);
System.out.println("Enter 20 numbers in the array : ");
for(int i=0;i<20;i++)
arr[i]=input.nextInt();
}
/* method selection sort for sorting the array */
public static void selectionSort(int[] arr){
for (int i = 0; i < 20 - 1; i++)
{
int index = i;
for (int j = i + 1; j < 20; j++){
if (arr[j] < arr[index]){
index = j;
}
}
int num = arr[index];
arr[index] = arr[i];
arr[i] = num;
}
}
/* method for searching and printing the position if number is found */
public static void search(int[] arr,int key){
int found=0;
int position=0;
for (int i = 0; i < arr.length; i++) {
if(key==arr[i]){
found=1;
position=i+1;
break;
}
}
if(found==1){
System.out.println("Element is found at "+position+" position");
}
else
System.out.println("Element is not found ");
}
public static void main(String []args){
int[] arr=new int[50];//defining array
Scanner input=new Scanner(System.in);
read(arr); //calling read method for taking input from user
selectionSort(arr); //calling selection sort method
System.out.println("Sorted array : "); //displaying sorted array
for(int i=0;i<20;i++)
System.out.print(arr[i]+" ");
//asking user to enter number to be search
System.out.println("Enter the number to search : ");
int key=input.nextInt();
//calling search method for searching
search(arr,key);
}
}
/* Note: Please ask in case of any doubt */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.