JAVA Insertion Sort Using ArrayList Problem description Write a program that rea
ID: 3834441 • Letter: J
Question
JAVA Insertion Sort Using ArrayList
Problem description
Write a program that reads 50 strings from a file and sorts them by inserting each string into the appropriate place in an ArrayList<String> object.For example, if the strings are:
Shai
Ralph
Hillary
Tom
Barbara
Fred
Then the ArrayList should grow as follows:
empty
Shai
Ralph Shai
Hillary Ralph Shai
Hillary Ralph Shai Tom
Barbara Hillary Ralph Shai Tom
Barbara Fred Hillary Ralph Shai Tom
Analyze the problem and design the class
Implement the class
Write a test class
Prepare the test file
Run the test and record the results
Explanation / Answer
Please find my implementation.
Please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
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) throws FileNotFoundException {
ArrayList<String> aryList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter input file name: ");
String file = sc.next();
Scanner fileScanner = new Scanner(new File(file));
while(fileScanner.hasNext()){
System.out.println(aryList);
insertionSortList(aryList, fileScanner.next());
}
System.out.println(aryList);
fileScanner.close();
sc.close();
}
}
/*
Sample run:
Enter input file name: names.txt
[]
[Shai]
[Ralph, Shai]
[Hillary, Ralph, Shai]
[Hillary, Ralph, Shai, Tom]
[Barbara, Hillary, Ralph, Shai, Tom]
[Barbara, Fred, Hillary, Ralph, Shai, Tom]
*/
######## names.txt ##########
Shai
Ralph
Hillary
Tom
Barbara
Fred
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.