In: Computer Science
Design a class named ArraySort and it contains the following method:
Public int search(int target): if the target is found in the array, return the number of its showing up. If the target is not found in the array, return -1. If the array is empty, return -1;
Public int maximum():Return the maximum number in the array if the array is nonempty, otherwise return -1;
Public int minimum(): Return the minimum number in the array if the array is nonempty, otherwise return -1;
Public int getElement(int index): Return the value at index. If index does not exist, throw an IndexOutOfBoundsException.
Public void setElement(int index, int value): Set the value at index. If index does not exist, throw an IndexOutOfBoundsException.
Public void addeElement(int value): Set the value in the cell at the end of the array. If array is full, you need to call the a private method to resize your array(double the size and copy all elements in original array to the new array).
Public void printArray(): Display all of elements in the array.
Public void delete(int value): Delete all the elements in the array with given value and reorganize the array without any empty spaces btw any two elements.
public class ArraySort
{
//data member declaration
int size;
private int[] array= new int[size];
//method to search and element
public int search(int target)
{
for(int i=0; i<array.length; i++)
{
if(array[i] == target)
return i;
}
return -1;
}
//method to find teh maximum value
public int maximum()
{
int max = array[0];
if(array.length>0)
{
for(int i=0; i<array.length; i++)
{
if(array[i] > max)
max = array[i];
}
return max;
}
return -1;
}
//method to find the minimum value
public int minimum()
{
int min = array[0];
if(array.length>0)
{
for(int i=0; i<array.length; i++)
{
if(array[i]<min)
min = array[i];
}
return min;
}
return -1;
}
//method to get the element at the index
public int getElement(int index)
{
int element = 0;
try
{
element = array[index];
}
catch(IndexOutOfBoundsException e)
{
System.out.println("The index is out of bound");
}
return element;
}
//method to set the elemtent
public void setElement(int index, int value)
{
try
{
array[index] = value;
}
catch(IndexOutOfBoundsException e)
{
System.out.println("The index is out of bound");
}
}
//method to add the element
public void addeElement(int value)
{
if(array.length >= size)
{
resizingArray(2*size);
size = 2*size;
}
array[size] = value;
}
//method to resize an array
private void resizingArray(int size)
{
this.size = size;
array = new int[size];
}
//method to print an array
public void printArray()
{
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
}
//method to delete an array element
public void delete(int value)
{
for(int i=0; i<array.length; i++)
{
if(array[i] == value)
{
for (int j = i; j < array.length-1; j++)
{
array[j] = array[j + 1];
}
}
}
}
}