public class OrderedStringArray { protected String data[]; protected int size; public OrderedStringArray(int initialArraySize) { size = 0; data = new String[initialArraySize]; } /** * Calculate the size of the ordered string array * @return The number of elements in the ordered string array */ public int size() { return size; } /** * Delete an element at a specified index, shifting all elements * at a larger index to the left. * @param index Index of the element to delete */ public void delete(int index) { size--; while (index < size) { data[index] = data[index + 1]; } } /** * Return an element at a specified index * @param index Index of the element return * @return the element at Index 'index' */ public String elementAt(int index) { return data[index]; } /** * Return true of the elements are in increasing order, and false otherwise * @return true If the list is in increasing order, false otherwise */ //public boolean inIncreasingOrder() // { // // } /** * Reverse the list, so that if it was originally in increasing order, it will now * be in decreasing order, and vice-versa */ // public void reverse() // { // } /** * Create a string representation of the list, which is an open bracket "[", followed * by all of the elements in the lists (separated by commas) followed by a closing bracket * "]" * @return String representation of the list */ public String toString() { String result = "["; for (int i = 0; i < size-1; i++) { result = result + data[i] + ","; } if (size > 0) { result = result + data[size-1]; } result += "]"; return result; } /** * Create a new array that is twice as large as the old array, and copy all the elements * from the old array to the new array. */ protected void doubleAllocatedSize() { String newData[] = new String[data.length * 2]; for (int i = 0; i < this.size; i++) { newData[i] = data[i]; } data = newData; } /** * Insert a string into the ordered list in the correct location. Copy all elements * that are greater than (for normal lists) or less than (for reversed lists) over * one space to the right to make space for the inserted element * @param element The string to insert into the list */ void insert(String element) { if (data.length == size) { doubleAllocatedSize(); } int insertIndex = size; while (insertIndex > 0 && data[insertIndex-1].compareTo(element) > 0) { data[insertIndex] = data[insertIndex - 1]; insertIndex--; } data[insertIndex] = element; size++; } public static void main(String args[]) { OrderedStringArray revArray = new OrderedStringArray(5); revArray.insert("dog"); revArray.insert("cat"); revArray.insert("ant"); revArray.insert("dog"); revArray.insert("bird"); revArray.insert("pig"); revArray.insert("dog"); revArray.insert("pig"); System.out.println("Original List:"); System.out.println(revArray); // revArray.reverse(); System.out.println("Reversed List:"); System.out.println(revArray); } }