Write a Java program that accepts as its first input a number that represents th
ID: 3700089 • Letter: W
Question
Write a Java program that accepts as its first input a number that represents the number of strings to be inserted followed by the Strings. The program should insert the strings into an array in its sorted position. The array should NOT be sorted after all elements are inserted rather it should be sorted after each individual element is inserted. Once all elements have been inserted print out the sorted array. Sort in ASCENDING order (A-Z).
You should have methods that do the following: Prints the array Places element in its sorted position
For this problem, do NOT use any class that manipulates data in a collection like the Arrays class or the Collection class
Explanation / Answer
import java.util.Scanner;
public class Main
{
public static void print(String array[], int size){
for(int i=0; i<size; i++){
System.out.println(array[i]);
}
}
// Main function
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberOfStrings;
numberOfStrings = sc.nextInt();
String sortedArray[] = new String[numberOfStrings];
String str;
for(int i=0; i<numberOfStrings; i++){
System.out.println("Enter string: ");
str = sc.nextLine();
System.out.println(i);
if(i==1){
sortedArray[i] = str;
}else{
// logic to insert in the array in sorted order
for(int j=1; j<i; j++){
System.out.println(sortedArray[j]);
int val = str.compareToIgnoreCase(sortedArray[j]);
if(val == 0){
break;
}else if(val > 0){
continue;
}else {
for(int k=i-1; k>j;k++){
sortedArray[k+1] = sortedArray[k];
}
sortedArray[j] = str;
break;
}
}
}
}
print(sortedArray,numberOfStrings);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.