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

JAVA help with two methods: Hi there, I have been struggling with these two meth

ID: 3847454 • Letter: J

Question

JAVA help with two methods:

Hi there, I have been struggling with these two methods for some time (this is my second post on here). I would really appreciate a thorough answer with explanations commented out in the code. The two methods I need are as follows:

Method 1:

insert(int): void

1.)insert an integer into the array so that the elements are in ascending order

2.) do not allow for duplicates in the array

3.) if the array is full, do not insert the value

4.) do not sort the array (don't use sorting algorithms)

Method two:

delete (int): void

1.) find the integer in the array and remove it

2.) if the value is not in the array, do nothing

3.) if the value is in the array, remove it so that the elements remain in ascending order

Explanation / Answer

Global Variables:

int[] list: Array of intigers in which we shall be storing the data

int count: Keep track of how many data are present in the list

Consideration:

Code:


    void insert(int n){
        if (count == size()) //this indicates the list is full, and insertion cannot take place
            return;


        int pos ; //pos indicates the position where data should be inserted
        for (pos = count; pos > 0; pos --) // find apt position for insertion
            if (list[pos-1] == n) //the function returns control to calling function when same number is found
                return; //so if the number was there in the list earlier, insertion will not take place
            else if (list[pos -1] < n) //once the item left of 'pos' is less than the item we want to insert is less
                break; //indicates we have found our position of insertion
        //once we have our position, we need to make a vacancy there. We achive it by shifting values right of 'pos' one position right       
        for (int i = count; i > pos; i--)// rigtht shift to make space for insertinf
            list[i] = list[i-1];
      
        list[pos] = n;//insert
      
        count ++;
    }
  
    void delete(int n) {
        int pos;
        for(pos = 0; pos < count; pos++) //find the position of victim
            if (list[pos] == n)
                break;
        //if item is not in list, pos becomes equal to count
        //and cannot enter the next loop
        for(int i = pos; i < count-1; i++) // left shift items from victim position to end
            list[i] = list[i+1];
      
        count --; //decrease count
    }