Problem
I have a very basic List Array of Strings scanned from a .txt file that I passed onto a insertionSort method to have it sorted Alphabetically but it seems to only sort the last 2 or 3 pairs of names towards the end of the Array List. I feel like it may be my while loop in the insertionSort method that is causing this using the compareTo() method to swap indices of Strings stored in the array.
Console Output
[James, Michael, Adam, Brenda, Margaret, Luke, Chantel, Enzo, Daniel, Lisa] <- original .txt list
[James, Michael, Adam, Brenda, Luke, Margaret, Chantel, Daniel, Enzo, Lisa] <- output
I just need help to understand an assignment and why my implementation is not working correctly for my Data Structures & Algorithms class. Any help is appreciated, thank you!!
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
import java.util.*;
public class Insert {
public static void insertionSort(List<String> list) {
for (int j = 1; j < list.size(); j++) {
String current = list.get(j);
int i = j-1;
while ((i > -1) && ((list.get(i).compareTo(current)) == 1)) {
list.set(i+1, list.get(i));
i--;
}
list.set(i+1, current);
}
System.out.print(list);
}
public static void main(String[] args) throws FileNotFoundException{
List<String> data = new ArrayList<>();
File inputFile = new File("customer.txt");
Scanner in = new Scanner(inputFile);
while (in.hasNextLine())
{
data.add(in.nextLine());
}
System.out.println(data);
Insert test = new Insert();
test.insertionSort(data);
}
}
insertionSort()
is a static method you can directly call it inmain()
without having to create thattest
instance first.compareTo
method can return a positive integer greater than 1.