Traversing a Sorted Linear Array
USER INPUT THE ARRAY SIZE
Inserting Item into Sorted Linear Array
insertItem()
Get value of ITEM to be inserted.
Call findLocationInsert()
findLocationInsert()
Search for position which ITEM can be inserted and Return position
Deleting item into Sorted Linear Array
deleteItem()
Get value of ITEM to be deleted
Call findLocationDelete()
findLocationDelete()
Search for the position in which ITEM will be deleted and return position
main() - Display option similar to this:
1. Insert value 2. Delete value 3. Traverse array 4. Exit
Provide switch statement which cases for the shown options are written.
array must be checked if it's already full or not.
Enter your choice: 1
Enter element to inserted: 5
Array Basic Operations
1. Insert a value
2. Delete a value
3. Traverse the array
4. Exit
Enter your choice: 1
Enter element to inserted: 3
Array Basic Operations
1. Insert value
2. Delete value
3. Traverse array
4. Exit
Enter your choice: 3
The elements of the array: 3 5
public class SortedLinearArray {
private int[] array;
private int currentSize;
public SortedLinearArray() {
this(10);
}
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 void printArray() {
System.out.print("The elements of the array: ");
for (int i = 0; i < currentSize; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
SortedLinearArray sortedLinearArray = new SortedLinearArray();
Scanner in = new Scanner(System.in);
String choice;
while (true) {
System.out.println("\n1. Insert a value"
+ "\n2. Delete a value"
+ "\n3. Traverse the array"
+ "\n4. Exit");
System.out.print("Enter your choice: ");
choice = in.nextLine();
switch (choice) {
case "1":
System.out.print("Enter element to inserted: ");
sortedLinearArray.insertItem(Integer.parseInt(in.nextLine()));
break;
case "2":
System.out.print("Enter element to deleted: ");
sortedLinearArray.deleteItem(Integer.parseInt(in.nextLine()));
break;
case "3":
sortedLinearArray.printArray();
break;
case "4":
System.exit(0);
}
}
}
}
Comments
Leave a comment