Question

Improve the code below by creating an addBefore method. Instead of adding an element to the...

Improve the code below by creating an addBefore method. Instead of adding an element to the end, addBefore adds it to the beginning, at position 0, causing all existing elements to move forward (their position increased by 1). However, like add, your addBefore method must also guarantee that only O(?) time is needed to perform n addBefores and adds. To accomplish this, as with add, most calls to addBefore must execute very quickly, in O(1) constant time, meaning that you can’t just shift all the elements forward by 1. The changes you make to IntArrayList should preserve the property that the get and set methods take a constant amount of time (not proportional to the array size) and the above property of add that only a linear number of elements is copied. (JAVA)

public class funtion {

private int[] a; // Underlying array

private int length; // Number of added elements in a

public IAList() {

length = 0; // Start with no added elements in a a = new int[4]; // A little room to grow

}

public int get(int i) { // Retrieve an added element, O(1)

if (i < 0 || i >= length) {

throw new ArrayIndexOutOfBoundsException(i);

}

return a[i]; // Retrieve the element at position i

}

public int size() { // Number of added elements, O(1)

return length; // The number of added elements

}

public void set(int i, int x) { // Modify an existing element, O(1)

if (i < 0 || i >= length) {

throw new ArrayIndexOutOfBoundsException(i);

}

a[i] = x; // Change the existing element at position i to x

}

public void add(int x) { // Add an element to the end, O(n) for n

if (length >= a.length) {

// Create new array of double the length

int[] b = new int[a.length * 2];

// Copy the elements of a to the corresponding indexes of b

for (int i = 0; i < a.length; i++) { b[i] = a[i];

}

// Reassign a reference to b a = b;

}

// Place x at the end of the IAList a[length] = x;

// Increase length by 1 length = length + 1;

}

public void addBefore(int x) { /* FILL THIS IN!! */

}

}

0 1
Add a comment Improve this question Transcribed image text
Answer #1

thanks for the question, here is the implemented method addBefore() and also corrected the comments incorrectly added

I added a new method printArray() and main () method to test its working fine. You can remove these two methods if you want

===========================================================================================

import java.util.Arrays;

public class IAList {

    private int[] a; // Underlying array

    private int length; // Number of added elements in a

    public IAList() {
        length = 0; // Start with no added elements in a
        a = new int[4]; // A little room to grow
    }

    public int get(int i) { // Retrieve an added element, O(1)
        if (i < 0 || i >= length) {
            throw new ArrayIndexOutOfBoundsException(i);
        }
        return a[i]; // Retrieve the element at position i
    }

    public int size() { // Number of added elements, O(1)
        return length; // The number of added elements
    }

    public void set(int i, int x) { // Modify an existing element, O(1)
        if (i < 0 || i >= length) {
            throw new ArrayIndexOutOfBoundsException(i);
        }
        a[i] = x; // Change the existing element at position i to x
    }

    public void add(int x) { // Add an element to the end, O(n) for n
        if (length >= a.length) {
            // Create new array of double the length
            int[] b = new int[a.length * 2];
            // Copy the elements of a to the corresponding indexes of b

            for (int i = 0; i < a.length; i++) {
                b[i] = a[i];
            }
            // Reassign a reference to b
            a = b;
        }

       // Place x at the end of the IAList
        a[length] = x;
        // Increase length by 1
        length = length + 1;
    }

    public void addBefore(int x) { /* FILL THIS IN!! */

        if (length >= a.length) {
            // Create new array of double the length
            int[] b = new int[a.length * 2];
            // Copy the elements of a to the corresponding indexes of b
            // starting at index 1 and leave index 0 for assigning the value of x at 0
            for (int i = 0; i < a.length; i++) {
                b[i+1] = a[i];
            }
            // Reassign a reference to b
            a = b;
        }else {
            System.out.println(length);
            for (int i = length-1;i>=0;i--) {
                // starting at index 1 and leave index 0 for assigning the value of x at 0
                a[i + 1] = a[i];
            }
        }
        a[0]=x;
        length = length + 1;
    }

    public void printArray(){
        System.out.println(Arrays.toString(a));
    }

    public static void main(String[] args) {
        IAList i = new IAList();
        i.add(1);i.printArray();
        i.add(2);i.printArray();
        i.add(3);i.printArray();
        i.addBefore(4);
        i.printArray();
        i.addBefore(5);
        i.printArray();
        i.addBefore(6);
        i.printArray();
        i.addBefore(7);
        i.printArray();
        i.addBefore(8);
        i.printArray();
        i.addBefore(9);
        i.printArray();

    }

}

======================================================================================

52 53 54 public void addBefore (int x) { /1 FILL THIS IN!! if (length >=a.length) { // Create new array of double the length

important lines are commented for your to understand. let me know in case you have any question.

thanks a lot !

Add a comment
Know the answer?
Add Answer to:
Improve the code below by creating an addBefore method. Instead of adding an element to the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java: Create an addBefore and add method to the class IntArrayList. The method addBefore adds...

    In Java: Create an addBefore and add method to the class IntArrayList. The method addBefore adds an element to the beginning of an array, at index 0, causing all existing elements to move forward (their indexes increased by 1). The method add creates an element at the end of the array. There are several ways to accomplish this task. Perhaps the easiest: double the array when you hit the beginning or end, copying it to the beginning or end dependent...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • PART 1 Modify the class ArrayList given in Exercise 1 by using expandable arrays. That is,...

    PART 1 Modify the class ArrayList given in Exercise 1 by using expandable arrays. That is, if the list is full when an item is being added to this list, the elements will be moved to a larger array. The new array should have twice the size of the original array. Using the new class ArrayList, write a program to store 1,000 random numbers, each in the interval [0, 500]. The initial size of the array in the class should...

  • Complete an Array-Based implementation of the ADT List including a main method and show that the...

    Complete an Array-Based implementation of the ADT List including a main method and show that the ADT List works. Draw a class diagram of the ADT List __________________________________________ public interface IntegerListInterface{ public boolean isEmpty(); //Determines whether a list is empty. //Precondition: None. //Postcondition: Returns true if the list is empty, //otherwise returns false. //Throws: None. public int size(); // Determines the length of a list. // Precondition: None. // Postcondition: Returns the number of items in this IntegerList. //Throws: None....

  • USE JAVA: Given the Interface Code and the Interface Implementation Code; Write Junit Tests to test...

    USE JAVA: Given the Interface Code and the Interface Implementation Code; Write Junit Tests to test all fuctionality. ------------- Interface code: public interface CustomList { /** * This method should add a new item into the CustomList and should * return true if it was successfully able to insert an item. * @param item the item to be added to the CustomList * @return true if item was successfully added, false if the item was not successfully added (note: it...

  • I hope someone can explain this exercise to me. Thanks +++++++++++++ Programming Exercise Try to think...

    I hope someone can explain this exercise to me. Thanks +++++++++++++ Programming Exercise Try to think about how to implement KWArrayList class. Please implement the following constructor and methods: public KWArrayList() public boolean add(E anEntry) public E get(int index) { public E set(int index, E newValue) public E remove(int index) private void reallocate() public int size() public int indexOf(Object item)       Study the code for ArrayList implementation (enclosed in the folder) and work on the following exercise Provide a constructor...

  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

  • Please merge all the codes below and add comments using JAVA Program. I need a complete...

    Please merge all the codes below and add comments using JAVA Program. I need a complete code which is the combination of the following codes: // Merges the left/right elements into a sorted result. // Precondition: left/right are sorted public static void merge(int[] result, int[] left,                                        int[] right) {     int i1 = 0;   // index into left array     int i2 = 0;   // index into right array     for (int i = 0; i < result.length; i++)...

  • (1) Implement the countKey(T element) method, which should return a count of the number of times...

    (1) Implement the countKey(T element) method, which should return a count of the number of times that the given key (the element) is found in the list. (2) Implement the indexOf(T element) method, which is similar as the indexOf method in the String class. It returns the index (the position starting from the head node) of the first occurrence of the given element, or -1, if the element does not occur in the list. You will need to track the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT