Question

In: Computer Science

Modify the method so that the item with the highest key is not only returned by...

Modify the method so that the item with the highest key is not only returned by the method but is also removed from the array.

Call the method removeMax().

// highArray.java
// demonstrates array class with high-level interface
// to run this program: C>java HighArrayApp
////////////////////////////////////////////////////////////////
class HighArray {
    private long[] a; // ref to array a
    private int nElems; // number of data items

    //-----------------------------------------------------------
    public HighArray(int max) // constructor
    {
        a = new long[max]; // create the array
        nElems = 0; // no items yet
    }

    //-----------------------------------------------------------
    public boolean find(long searchKey) { // find specified value
        int j;
        for (j = 0; j < nElems; j++) // for each element,
            if (a[j] == searchKey) // found item?
                break; // exit loop before end
        if (j == nElems) // gone to end?
            return false; // yes, can't find it
        else
            return true; // no, found it
    } // end find()

    //-----------------------------------------------------------
    public void insert(long value) // put element into array
    {
        a[nElems] = value; // insert it
        nElems++; // increment size
    }

    //-----------------------------------------------------------
    public boolean delete(long value) {
        int j;
        for (j = 0; j < nElems; j++) // look for it
            if (value == a[j])
                break;
        if (j == nElems) // can't find it
            return false;
        else // found it
        {
            for (int k = j; k < nElems; k++) // move higher ones down
                a[k] = a[k + 1];
            nElems--; // decrement size
            return true;
        }
    } // end delete()

    //-----------------------------------------------------------
    public void display() // displays array contents
    {
        for (int j = 0; j < nElems; j++) // for each element,
            System.out.print(a[j] + " "); // display it
        System.out.println("");
    }

    public long getMax() {
        if (nElems == 0) {
            return -1;
        } else {
            long max = a[0];
            for (int i = 0; i < nElems; i++) {
                if (a[i] > max) {
                    max = a[i];
                }
            }
            return max;
        }
    }
//-----------------------------------------------------------
} // end class HighArray

////////////////////////////////////////////////////////////////
class HighArrayApp {
    public static void main(String[] args) {
        int maxSize = 100; // array size
        HighArray arr; // reference to array
        arr = new HighArray(maxSize); // create the array
        arr.insert(77); // insert 10 items
        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);
        arr.display(); // display items
        int searchKey = 35; // search for item
        if (arr.find(searchKey))
            System.out.println("Found " + searchKey);
        else
            System.out.println("Can't find " + searchKey);
        arr.delete(00); // delete 3 items
        arr.delete(55);
        arr.delete(99);
        arr.display(); // display items again

        System.out.println("Max in array is " + arr.getMax());
    } // end main()
} // end class HighArrayApp

Solutions

Expert Solution

// highArray.java
// demonstrates array class with high-level interface
// to run this program: C>java HighArrayApp
////////////////////////////////////////////////////////////////
class HighArray {
    private long[] a; // ref to array a
    private int nElems; // number of data items

    //-----------------------------------------------------------
    public HighArray(int max) // constructor
    {
        a = new long[max]; // create the array
        nElems = 0; // no items yet
    }

    //-----------------------------------------------------------
    public boolean find(long searchKey) { // find specified value
        int j;
        for (j = 0; j < nElems; j++) // for each element,
            if (a[j] == searchKey) // found item?
                break; // exit loop before end
        if (j == nElems) // gone to end?
            return false; // yes, can't find it
        else
            return true; // no, found it
    } // end find()

    //-----------------------------------------------------------
    public void insert(long value) // put element into array
    {
        a[nElems] = value; // insert it
        nElems++; // increment size
    }

    //-----------------------------------------------------------
    public boolean delete(long value) {
        int j;
        for (j = 0; j < nElems; j++) // look for it
            if (value == a[j])
                break;
        if (j == nElems) // can't find it
            return false;
        else // found it
        {
            for (int k = j; k < nElems; k++) // move higher ones down
                a[k] = a[k + 1];
            nElems--; // decrement size
            return true;
        }
    } // end delete()

    //-----------------------------------------------------------
    public void display() // displays array contents
    {
        for (int j = 0; j < nElems; j++) // for each element,
            System.out.print(a[j] + " "); // display it
        System.out.println("");
    }

    public long getMax() {
        if (nElems == 0) {
            return -1;
        } else {
            long max = a[0];
            for (int i = 0; i < nElems; i++) {
                if (a[i] > max) {
                    max = a[i];
                }
            }
            return max;
        }
    }

    public long removeMax() {
        if (nElems == 0) {
            return -1;
        } else {
            int maxIndex = 0;
            for (int i = 0; i < nElems; i++) {
                if (a[i] > a[maxIndex]) {
                    maxIndex = i;
                }
            }
            long result = a[maxIndex];
            for (int i = maxIndex; i < nElems - 1; i++) {
                a[i] = a[i + 1];
            }
            nElems--;
            return result;
        }
    }
//-----------------------------------------------------------
} // end class HighArray

////////////////////////////////////////////////////////////////
class HighArrayApp {
    public static void main(String[] args) {
        int maxSize = 100; // array size
        HighArray arr; // reference to array
        arr = new HighArray(maxSize); // create the array
        arr.insert(77); // insert 10 items
        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);
        arr.display(); // display items
        int searchKey = 35; // search for item
        if (arr.find(searchKey))
            System.out.println("Found " + searchKey);
        else
            System.out.println("Can't find " + searchKey);
        arr.delete(00); // delete 3 items
        arr.delete(55);
        arr.delete(99);
        arr.display(); // display items again

        System.out.println("Max in array is " + arr.removeMax());
        System.out.println("Next Max in array is " + arr.removeMax());
    } // end main()
} // end class HighArrayApp

Related Solutions

Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right)...
Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right) element as the pivot, rather than an arbitrary number. (This is similar to what happens in the quickSort1.java program in Listing 7.3.) Make sure your routine will work for arrays of three or fewer elements. To do so, you may need a few extra statements. // partition.java // demonstrates partitioning an array // to run this program: C>java PartitionApp //////////////////////////////////////////////////////////////// class ArrayPar { private...
Modify the processFile method so that it will compile and it will not produce a runtime...
Modify the processFile method so that it will compile and it will not produce a runtime error: public static void processFile(File file) { File input = "contents.txt"; String line = null; try { input = new File(file); while ((line = input.readLine()) != null) { System.out.println(line); } return; } finally { if (file != null) { file.close(); } } }
Modify the insertionSort() method in insertSort.java so it counts the number of copies and the number...
Modify the insertionSort() method in insertSort.java so it counts the number of copies and the number of comparisons it makes during a sort and displays the totals. To count comparisons, you will need to break up the double condition in the inner while loop. Use this program to measure the number of copies and comparisons for different amounts of inversely sorted data. Do the results verify O(N2 ) efficiency? Do the same for almost-sorted data (only a few items out...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only run if the account status is active. You can do this adding a Boolean data member ‘active’ which describes account status (active or inactive). A private method isActive should also be added to check ‘active’ data member. This data member is set to be true in the constructor, i.e. the account is active the first time class Account is created. Add another private method...
Java instructions: 1. Modify abstract superclass (Employee10A) so it comment out the abstract payPrint method and...
Java instructions: 1. Modify abstract superclass (Employee10A) so it comment out the abstract payPrint method and uses a toString method to print out it’s instance variables. Make sure toString method cannot be overridden.​​​​​​ Source code below: public abstract class Employee10A {    private String firstName, lastName; static int counter = 0;    public Employee10A(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }    @Override public String toString() { return ("The employee's full name is " + firstName...
Provide immediate feedback for each mistyped sentence. To do so, modify the Test class’s present_test method...
Provide immediate feedback for each mistyped sentence. To do so, modify the Test class’s present_test method so that it informs the player a mistake has been made, then display the challenge sentence followed by the player’s sentence so the player can determine where the error lies. #-------------------------------------------------------------------------- # # Script Name: TypingChallenge.rb # Version: 1.0 # Author: Jerry Lee Ford, Jr. # Date: March 2010 # # Description: This Ruby script demonstrates how to apply conditional logic # in order...
Match each function to the correct item. Answers can only be used once, so choose the...
Match each function to the correct item. Answers can only be used once, so choose the BEST answer. Question Generator potential Touch Acuity Smell Transmits sensory information about proprioception to cortex All Answer Choices A. Chemoreceptor B. Interneuron C. Autonomic nervous system D. Receptor density E. Mechanoreceptor F. Afferent neuron G. Efferent neuron H. Electroreceptor I. Dorsal Column
in C++, Modify the quicksort algorithm such that it uses the last item as the pivot...
in C++, Modify the quicksort algorithm such that it uses the last item as the pivot instead of the 1st. Also, sort in descending order, instead of ascending order. NOTE: Do not move the last element into the first element of the array. You must treat the algorithm as if the pivot is actually sitting in the last location of the array. After it has been sorted in descending order, go through all the items in the array and make...
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when...
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when the program runs. Have the program request the number of initial numbers to be entered." //C++ Program 7.14 as follows #include #include #include #include using namespace std; int main() { const int NUMELS = 4; int n[] = {136, 122, 109, 146}; int i; vector partnums(n, n + NUMELS); cout << "\nThe vector initially has the size of " << int(partnums.size()) << ",\n and...
Modify the Movie List 2D program -Modify the program so it contains four columns: name, year,...
Modify the Movie List 2D program -Modify the program so it contains four columns: name, year, price and rating (G,PG,R…) -Enhance the program so it provides a find by rating function that lists all of the movies that have a specified rating def list(movie_list): if len(movie_list) == 0: print("There are no movies in the list.\n") return else: i = 1 for row in movie_list: print(str(i) + ". " + row[0] + " (" + str(row[1]) + ")") i += 1...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT