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

Modify the insert method in OurArray to add a new element so that the order is m

ID: 3750846 • Letter: M

Question

Modify the insert method in OurArray to add a new element so that the order is maintained.

The smallest value will always be at index 0 and the largest at indcex size-1.

if the content of the array was -2, 3, 5, 8. If we insert 6 then 6 should go between 5 and 8.

First find where to add the value move everything from that index up then add the value at that index.

//optionally

write a method remove that accepts the index of the value to be removed int remove (int index). If the index is not valid display an error message and return 0.

Obj1.insert(-2);//-2
        Obj1.insert(5);//-2, 5
        Obj1.insert(-6);// -6,-2, 5
        Obj1.insert(7);//-6, -2, 5, 7
        //-6, -2, 5, 7

Explanation / Answer

public class OurArray {
private int[] MyArray;
private int size;

public OurArray() {
//default size 100
MyArray=new int[100];
size=0;
}
public OurArray(int c) {
//else array size c
MyArray=new int[c];
size=0;
}
public int getSize(){
return size;
}
//modified methos to inserted at sorted index
public void insert(int value){
if(size>=MyArray.length){
System.out.println("Array full not enough space");
}
else{

int ind=0;
boolean flag=true;
for(int a:MyArray){
if(a>=value)
{
flag=false;
//Insertion point found
break;
}
else
ind++;
}
//
for(int i=MyArray.length-1;i>ind;i--){
MyArray[i]=MyArray[i-1];
}
if(flag)
MyArray[size]=value;
else
MyArray[ind]=value;
size++;
}
}
public int remove(int index){
if(index>size||size==0){
System.out.println("Array Empty Can't remove");
System.exit(1);
}
int data =MyArray[index];
for(int i=index;i<size;i++)
MyArray[i]=MyArray[i+1];
size--;
return data;
}
public void display(){
for(int i=0;i<size;i++){
System.out.println("MyArray["+i+"] ="+MyArray[i]);
}
}

}

//Driver class to check functionality

public class CheggTest {


public static void main(String[] args) {

OurArray o=new OurArray(5);
o.insert(-2);
o.insert(5);
o.insert(-6);
o.insert(7);
System.out.println("After Insertion Array Contains:");
o.display();
System.out.println("After Removel at index 2 Array Contains:");
o.remove(2);
o.display();
//Insert data 8
o.insert(8);
System.out.println("After Insertion Array Contains:");
o.display();
}

}

Output:

After Insertion Array Contains:
MyArray[0] =-6
MyArray[1] =-2
MyArray[2] =5
MyArray[3] =7
After Removel at index 2 Array Contains:
MyArray[0] =-6
MyArray[1] =-2
MyArray[2] =7
After Insertion Array Contains:
MyArray[0] =-6
MyArray[1] =-2
MyArray[2] =7
MyArray[3] =8

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote