Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need a method that sorts an arraylist using insertion into an initially empty

ID: 3789647 • Letter: I

Question

I need a method that sorts an arraylist using insertion into an initially empty list (Also do not insert duplicate words)

This is what I have so far, however, it does not prevent insertion of duplicate words and I dont know how to make it insert into an initially empty list.

public static void insertionSortAList(ArrayList<String> list) {
for (int i = 1; i < list.size(); i++) {
/**
* insert list[i] into a sorted sublist list[0..i-1] so that
* list[0..i] is sorted.
*/
String currentElement = list.get(i);
int k;

for (k = i - 1; k >= 0 && list.get(k).compareTo(currentElement) > 0; k--) {
list.set(k+1, list.get(k));
}

// Insert the current element into list[k+1]
list.set(k+1, currentElement);
}
}

Explanation / Answer

You can use rmdup() function to remove duplicate from ArrayList.

Another way to remove duplicate you can use LinkList as it's not alllowed dplicate.

public static ArrayList<String> rmDup(ArrayList<String> list) {

        // Store unique items in result.
        ArrayList<String> result = new ArrayList<>();

        // Record encountered Strings in HashSet.
        HashSet<String> set = new HashSet<>();

        // Loop over argument list.
        for (String item : list) {

            // If String is not in set, add it to the list and the set.
            if (!set.contains(item)) {
                result.add(item);
                set.add(item);
            }
        }
        return result;
    }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote