Data structure and algorithm 4

In this program, the find() method in the HighArray class passes the value of the data item as a parameter, and its return value determines whether the data item is found.

The insert() method places a new data item in the next empty position of the array. A field named nElems keeps track of the number of data items in the array.

The delete() method looks for the corresponding data item based on the keyword passed in as a parameter. When he finds the data item, he moves all the subsequent data items forward, so as to overwrite the data item and delete it.

In this program, the class user HighArrayAPP does not need to consider the array subscript, because the structure is hidden, so it does not need to consider which data structure is used to store data in HighArray.

The main method is very concise.

class HighArray {
 private long[] a;
 private int nElems;
 
 // constructor
 public HighArray(int max) {
  a = new long[max];
  nElems = 0;
 }
 
 // find specified value
 public boolean find(long searchKey) {
  int j;
  for(j=0; j<nElems; j++) {
   if(a[j] == searchKey) {
    break;
   }
  }
     if(j == nElems) {
      return false;
     }
     else {
      return true;
     }
 }  // end find()
 
 // put element into array
 public void insert(long value) {
  a[nElems] = value;
  nElems++;
 }
 
 // delete specified value
 public boolean delete(long value) {
  int j;
  for(j=0; j<nElems; j++) {    // look for it
   if(value == a[j]) {
    break;
   }
  }
  if(j == nElems) {
   return false;            // can't find it
  }
  else {
   for(int k=j; k<nElems; k++) {
    a[k] = a[k+1];         // move higher ones down
   }
   nElems--;
   return true;
  }
 }  // end delete()
 
 // display items
 public void display() {
  for(int j=0; j<nElems; j++) {
   System.out.print(a[j] + " ");
  }
  System.out.println("");
 } // end display()

} // end class HighArray

class HighArrayApp {
 public static void main(String[] args) {
  int maxSize = 100;
  HighArray arr;
  arr = new HighArray(maxSize);
  
  // insert 10 items
  arr.insert(77);
  arr.insert(99);
  arr.insert(44);
  arr.insert(55);
  arr.insert(22);
  arr.insert(88);
  arr.insert(11);
  arr.insert(00);
  arr.insert(66);
  arr.insert(33);
  
  // display items
  arr.display();
  
  // search for item 35
  int searchKey = 35;
  if(arr.find(searchKey)) {
   System.out.println("Found " + searchKey);
  }
  else {
   System.out.println("Can't find " + searchKey);
  }
  
  // delete 3 items
  arr.delete(00);
  arr.delete(55);
  arr.delete(99);
  
  // display items
  arr.display();
  
 }  // end main()
} // end class HighArrayApp
77 99 44 55 22 88 11 0 66 33 
Can't find 35
77 44 22 88 11 66 33 

Posted on Sat, 08 Feb 2020 12:52:39 -0500 by genericnumber1