Comm Data Structures

profileAbdullah-sunul
P1-2_sortedArrayAccess.java

package p5_SortedArrayAccess; import java.util.*; public class sortedArrayAccess { public static double[] arr; private int arraySize; public sortedArrayAccess(int scale) { arr = new double[scale]; arraySize = 0; } public final double get(int i) { return arr[i]; } public final int BinarySearch(double Key) { int k = 0; int lower = 0; int upper = arraySize - 1; while (lower < upper) { k = (lower + upper + 1) / 2; if (Key == arr[k]) { break; } if (Key < arr[k]) { upper = k - 1; } else { lower = k + 1; } } if (lower == upper) { k = lower; } if (Key == arr[k]) { return k; } else { System.out.println("The item cannot be found!"); return -1; } } public final void insertion(double Key, double Item) { if (arraySize == 0) { arr[0] = Item; } /* find the position for interting the given item */ int position = 0; while (Key > arr[position] && position < arraySize) { position++; } for (int i = arraySize; i > position; i--) { arr[i] = arr[i - 1]; } arr[position] = Item; arraySize = arraySize + 1; } public final void deletion(double Key) { /* find the given item */ int position = BinarySearch(Key); if (position != -1) { for (int i = position; i < arraySize - 1; i++) { arr[i] = arr[i + 1]; } arraySize = arraySize - 1; }; } public final void display() { if (arraySize != 0) { for (int i = 0; i < arraySize; i++) { System.out.println(arr[i]); } }; System.out.println("The number of items is " + arraySize); } }