Part A) Java Programming Exercise #2: Write a method, remove, that takes three p
ID: 666803 • Letter: P
Question
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (Note that after deleting the element, the array size is reduced by 1.) Here you assume the array is not sorted. Do not sort the array.
Part B) Re-do Exercise #2 and name it Exercise2b. This time use a Bubble Sort to sort the array and then remove the item with the array sorted. Create a method for the BubbleSort.
Part C) Re-do Exercise #2 and name it Exercise 2c. This time use an insertion sort as given in this chapter to sort the array and then remove the item with the array sorted. Create a method for the insertion sort.
Make sure to test your array with a small array of 5 integers and a larger array of at least 25 integers. When testing, test the removal of the first item in the array, somewhere in the middle and the last item in the array.
For Part A, another question exactly like this one was posted and suggested that this is the java code:
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
int[] arr = {1,2,3,4,5,6,7,8,9};
for(int x: arr){
System.out.print(x + " ");
}
System.out.println();
arr = remove(arr, 9, 0);
for(int x: arr){
System.out.print(x + " ");
}
}
public static int[] remove(int[] array, int length, int removeItem){
int[] newArray = new int[length-1];
int temp = -1;
for(int i=0; i < length; i++){
if(array[i] == removeItem){
temp = i;
break;
}
}
if(temp == -1){
System.out.println("Element not found");
return array;
}
int j= 0;
for(int i=0; i<length; i++){
if(temp == i){
continue;
}
newArray[j] = array[i];
j++;
}
return newArray;
}
}
Explanation / Answer
Answer:
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
int[] arr = {1,2,3,4,5,6,7,8,9};
for(int x: arr){
System.out.print(x + " ");
}
System.out.println();
// Add below function for bubble sort
bubble_srt(int arr[])
// Add below function for insertion sort
insertionSort(int arr[])
arr = remove(array, 9, 0);
for(int x: arr){
System.out.print(x + " ");
}
}
//Bubble sort
public static int[] bubble_srt(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (array[i] > array[k]) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
return(array);
}
}
//insertion sort
public static int[] insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
return(array);
}
}