Please explain this code or simulate this.
public SortedLinearArray(int size) {
array = new int[size];
currentSize = 0;
}
public void insertItem(int item) {
if (currentSize < array.length) {
int insertLocation = findLocationInsert(item);
for (int i = currentSize - 1; i >= insertLocation; i--) {
array[i + 1] = array[i];
}
array[insertLocation] = item;
currentSize++;
}
}
private int findLocationInsert(int item) {
for (int i = 0; i < currentSize; i++) {
if (array[i] > item) {
return i;
}
}
return currentSize;
}
public void deleteItem(int item) {
int deleteLocation = findLocationDelete(item);
if (deleteLocation != -1) {
for (int i = deleteLocation + 1; i < currentSize; i++) {
array[i - 1] = array[i];
}
currentSize--;
}
}
private int findLocationDelete(int item) {
for (int i = 0; i < currentSize; i++) {
if (array[i] == item) {
return i;
}
}
return -1;
}
public class Main
{
public static void main(String[] args) {
SortedLinearArray s =new SortedLinearArray(5);
s.insertItem(34);
}
}
class SortedLinearArray {
//declare an array of int type
private int [] array;
//declare the current size
int currentSize;
//declare a constructor to initialize the size of the array and the current size
public SortedLinearArray(int size) {
array = new int[size];
currentSize = 0;
}
//define a function to insert an item in the array
public void insertItem(int item) {
if (currentSize < array.length) {
int insertLocation = findLocationInsert(item);
for (int i = currentSize - 1; i >= insertLocation; i--) {
array[i + 1] = array[i];
}
array[insertLocation] = item;
currentSize++;
}
}
//define a function to find a location in the array to insert an item into the array
private int findLocationInsert(int item) {
for (int i = 0; i < currentSize; i++) {
if (array[i] > item) {
return i;
}
}
return currentSize;
}
//define a function to delete an item from the array
public void deleteItem(int item) {
int deleteLocation = findLocationDelete(item);
if (deleteLocation != -1) {
for (int i = deleteLocation + 1; i < currentSize; i++) {
array[i - 1] = array[i];
}
currentSize--;
}
}
//define a function to find location to delete from the array
private int findLocationDelete(int item) {
for (int i = 0; i < currentSize; i++) {
if (array[i] == item) {
return i;
}
}
return -1;
}
}
Comments
Leave a comment