In: Computer Science
Java Searching and Sorting, please I need the Code and the Output.
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.
Ans
code:-
class MyClass {
public static void remove(int array[],int length,int removeItem){
int i;//iterate array and search
for(i=0;i<length;i++){
//if found then break
if(array[i]==removeItem){
break;
}
if(i==length-1)
{//if not found
System.out.println("Not found");
break;
}
}//shift elements left by 1 place
for(int j=i+1;j<length;j++){
array[j-1]=array[j];//shift
}
}//for running the above function
public static void main(String[ ] args) {
int array[]={1,2,3,5,6};//array of ints
remove(array,5,2);//call function
for(int i=0;i<4;i++)//print elements
System.out.print(array[i]+" ");
}
}
.
Output with code:-
.
.
If any doubt ask in the comments.