This is java Write a method, remove, that takes three parameters: an array of in
ID: 3829996 • Letter: T
Question
This is java
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. ( After deleting an element, the number of elements in the array is reduced by 1.) Assume that the array is unsorted.
**** 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.**
Explanation / Answer
import java.util.*;
class Test
{
public static void bubblesort(int[] array,int n)
{
int temp;
for(int i=0;i<n;i++)
{
for(int j=1;j<n-i;j++)
{
if(array[j-1] > array[j]) // compare elements and swap if they are not in ascending order
{
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
public static int remove(int[] array,int length1,int removeItem)
{
int flag = 0;
for(int i=0;i<length1;i++)
{
if(array[i] == removeItem)//if item exists in array
{
for(int j=i;j<length1-1;j++) // shift elements to left side reducing the size of array by 1
{
array[j]= array[j+1];
}
flag = 1; // flag = 1 shows item exists in the list
}
}
if(flag ==0)
{
System.out.println(" Element "+removeItem+" does not exists in the array");
}
else
length1--;
return length1;
}
public static void main (String[] args)
{
int[] array = {56,63,18,98,26,78,44,39,27,11};
bubblesort(array,10);
System.out.println(" Sorted array : ");
for(int i=0;i<10;i++)
{
System.out.print(array[i]+" ");
}
int length1 = remove(array,10,26);
System.out.println(" array after removing element: ");
for(int i=0;i<length1;i++)
{
System.out.print(array[i]+" ");
}
}
}
Output:
Sorted array :
11 18 26 27 39 44 56 63 78 98
array after removing element :
11 18 27 39 44 56 63 78 98
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.