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

How to sort a String ArrayList using insertion sort method into an initially emp

ID: 3789133 • Letter: H

Question

How to sort a String ArrayList using insertion sort method into an initially empty list. Do not insert duplicate words. Java Im having trouble understanding how to make a method that takes an arraylist and sorts it this way. Please do not ignore the bold parts of the question. I know how to do a standard insertion sort for an ArrayList, im having trouble understanding what I bolded. PLEASE, THIS IS THE 4th TIME POSTING THIS AND EVERY SINGLE TIME I GET THE WRONG ANSWER. I need an insertion sort method that takes an arrayList and sorts it into an initially empty list and does not insert more than one of ech word ------ sorts it into an initially empty list and does not insert more than one of each word------- sorts it into an initially empty list and does not insert more than one of each word--------sorts it into an initially empty list and does not insert more than one of ech word I REPEAT ----sorts it into an initially empty list and does not insert more than one of each word

Also ARRAYLIST NOT ARRAY --- I REPEAT ARRAYLIST..I dont want to keep wasting my questions

Thank you

Explanation / Answer

HI, Please find my method.

Please let me know in case of any issue.

import java.util.ArrayList;

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<>();

       String[] arr = {"Ram", "Apple", "Mango", "Ball", "Zebra"};

       for(int i=0; i<arr.length; i++){

           insertionSortList(aryList, arr[i]);

           System.out.println(aryList);

       }

   }

}

/*

Sample run:

[Ram]

[Apple, Ram]

[Apple, Mango, Ram]

[Apple, Ball, Mango, Ram]

[Apple, Ball, Mango, Ram, Zebra]

*/

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