Package array;/** * Sorts an array, maintaining the order of the array when adding elements to the array; * @author WL * */public class Myorderarray {private long array[];p rivate int E lements;//is used to record the number of actual data in an array public myorderarray () {array=new long[50];//array default length is 50;}public myorderarray (int capacity) {// Sets the default length of the array array=new long[capacity];} /** * Inserts elements into an array and maintains the ordering of elements in the array */public void Add (Long data) {if (elements>array.length-1) {throw new ArrayIndexOutOfBoundsException ();} int I;for (i=0;i<elements;i++) {if (array[i]>data) {break;}} for (int j=elements;j>i;j--) {array[j]=array[j-1];} array[i]=data;elements++;} /** * Delete element at index * @param index */public void Delete (int index) {if (index>=array.length| | index<0) {throw new Indexoutofboundsexception ();} for (int i=index;i<=elements;i++) {array[i]=array[i+1];} elements--;} /** * Delete element data * @param data */public void Delete (Long data) {int Addr=search (data), if (addr==-1) {System.out.println (data+ "does not exist");} else{for (int i=addr;i<=elements;i++) {array[i]=array[i+1];} elements--;}} /** * Find the subscript position of data in the array using binary lookup (binary lookup) * @param dATA * @return */public int binarysearch (Long data) {int Low,high,mid;low=0;high=elements;while (Low<=high) {mid=low+ ( high-low)/2;if (Data<array[mid]) {high=mid-1;} else if (Data>array[mid]) {low=mid+1;} Else{return Mid;}} return-1;} /** * Find element at index * @param index * @return */public long Search (int index) {if (index>=array.length| | index<0) {throw new Indexoutofboundsexception ();} return Array[index];} /** * Find the subscript for the data value in array * @param data * @return */public int search (Long data) {int i;for (i=0;i<=elements;i++) {if (array[ I]==data) {return i;}} return-1;} /** * Prints the contents of the array */public void display () {System.out.print ("["); for (int i=0;i<elements-1;i++) {System.out.print (array [i]+ ",");} System.out.print (Array[elements-1]); System.out.println ("]");}}
Java Data Structure Series--Arrays (2): Ordered arrays