Skip to content

Instantly share code, notes, and snippets.

@theoperatore
Last active December 14, 2015 14:38
Show Gist options
  • Save theoperatore/5101544 to your computer and use it in GitHub Desktop.
Save theoperatore/5101544 to your computer and use it in GitHub Desktop.
Add methods from a ShadowArray ADT and a BruteArrayADT
//int numItems ==> int to hold the number of Items in each underlying array
//E[] items ==> the data structure used in the BruteArray ADT
public void add(E item) {
//if the array needs to be expanded
if (numItems >= items.length) {
//create a new array that is twice as long
E[] brute = (E[])(new Object[items.length * 2]);
//copy over all existing elements
for (int i = 0; i < items.length; i++) {
brute[i] = items[i];
}
//add the new element
brute[numItems] = item;
//make the underlying array point at the new, larger array
items = brute;
}
//if not expansion...
else {
//just add the new item
items[numItems] = item;
}
//either way, item is added; increase count
numItems++;
}
//int numItems ==> int to hold the number of Items in each underlying array
//int carryIndex ==> Index to copy over pre-existing elements to new shadow array
//E[] k ==> the data structure used in the ShadowArray ADT
//E[] s ==> the shadow array data structure used in the ShadowArray ADT
public void add(E item) {
//if expansion is needed...
if (numItems >= k.length) {
//set the k array to the shadow array
k = s;
//create a new larger shadow array
s = (E[])(new Object[2*k.length]);
//reset the index to copy over pre-existing elements
carryIndex = 0;
//add the new item to both arrays
k[numItems] = item;
s[numItems] = item;
//copy over the first pre-existing element to the
//new shadow array
s[carryIndex] = k[carryIndex];
}
//if no expansion needed...
else {
//add the new item to both arrays
k[numItems] = item;
s[numItems] = item;
//copy over pre-existing elements
s[carryIndex] = k[carryIndex];
}
//increase both counts
carryIndex++;
numItems++;
}
//Same method is used for testing the BruteArray;
//just replace every instance of ShadowArray with BruteArray
public static void main(String[] args) {
ShadowArray<String> shadow = new ShadowArray<Sring>();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
shadow.add("arg");
}
long diff = System.currentTimeMillis() - start;
System.out.println("Insertion Difference: " + diff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment