Lab2 Question 2

public class Sorter {

    /**
    Implement a method that takes as input a reference to a sorted array of String objects,
    an integer representing the number of vali
d String objects contained in the array, and a
    new String object to be inserted into the array.  The method will insert the new St
ring
    object at the appropriate location and resize the array if necessary.  The method returns
    a reference to the new array.

    */
    public static String[] insertSorted(String[] stringlist, int numstrings, String newstring) {

    }

    /**
       Method used for testing.
       Prints contents of array passed as input.
     */
    public static void printArray(String[] strings, int count) {
        for(int i = 0; i < count; i++) {
            System.out.print(strings[i] + "\t");
        }
        System.out.println("\n**************");
    }

    /**
       Main method used for testing.
       Expected output:
       Bob
       **************
       Bob     Ed
       **************
       Ann     Bob     Ed
       **************
       Ann     Bob     Carl    Ed
       **************
       Ann     Bob     Carl    Dan     Ed
       **************
       Ann     Bob     Carl    Dan     Ed      Frank
       **************
     */
    public static void main(String[] args) {
        String[] strings = new String[5];
        int count = 0;

        //testing insert first string
        strings = insertSorted(strings, count, "Bob");
        count += 1;
        printArray(strings, count);

        //testing insert at end
        strings = insertSorted(strings, count, "Ed");
        count += 1;
        printArray(strings, count);

        //testing insert at beginning
        strings = insertSorted(strings, count, "Ann");
        count += 1;
        printArray(strings, count);

        //testing insert in middle
        strings = insertSorted(strings, count, "Carl");
        count += 1;
        printArray(strings, count);

        //testing insert in middle
        strings = insertSorted(strings, count, "Dan");
        count += 1;
        printArray(strings, count);

        //testing increase size
        strings = insertSorted(strings, count, "Frank");
        count += 1;
        printArray(strings, count);

    }
}

Comments