The objective of this exercise is to write a program that reads a number of Stri
ID: 3814896 • Letter: T
Question
The objective of this exercise is to write a program that reads a number of Strings and sorts them by inserting each string into the appropriate place in an array list. The algorithm to sort is simple. As you read each name (say name1), compare it with each name (say name2) stored in the arraylist starting from the index 0. As soon (name1.compareTo(name2) >0), that is the right index to put name1. Be sure that you do not cross the ArrayList boundary.
*I am using JGrasp so please make sure it is compatible *Please comment throughout code *FULL QUESTION IN IMAGES BELOW
The objective of this exercise is to write a program that reads a number of Strings and sorts them by inserting each string into the appropriate place in an arraylist. For example, if the strings are:Explanation / Answer
HI, Please find my implemetation.
import java.util.ArrayList;
import java.util.Scanner;
public class InsertInSortedOrder {
public static void insertionSortList(ArrayList<String> aryList, String element){
if(! aryList.contains(element)){
// edge case: Size one list, number coming in is smaller.
if(aryList.size() == 0 || aryList.get(0).compareTo(element) > 0) {
aryList.add(0, element);
} else if(aryList.get(aryList.size()-1).compareTo(element) < 0){
aryList.add(element);
}
else {
//System.out.println(element);
for(int i = 0; i < aryList.size()-1; i++) {
if(aryList.get(i).compareTo(element) < 0 && element.compareTo(aryList.get(i+1)) < 0) {
aryList.add(i+1, element);
break;
}
}
}
}
}
public static void main(String[] args) {
ArrayList<String> aryList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String name;
while(true){
System.out.println(aryList);
System.out.print("Enter name (exit to stop): ");
name = sc.next();
if("exit".equalsIgnoreCase(name))
break;
insertionSortList(aryList, name);
}
System.out.println(aryList);
}
}
/*
Sample run:
[]
[Shai]
[Ralph, Shai]
[Hillary, Ralph, Shai]
[Hillary, Ralph, Shai, Tom]
[Barbara, Hillary, Ralph, Shai, Tom]
[Barbara, Fred, Hillary, Ralph, Shai, Tom]
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.