Question

In: Computer Science

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 long[] theArray; // ref to array theArray
private int nElems; // number of data items
//--------------------------------------------------------------
public ArrayPar(int max) // constructor
{
theArray = new long[max]; // create the array
nElems = 0; // no items yet
}

//--------------------------------------------------------------
public void insert(long value) // put element into array
{
theArray[nElems] = value; // insert it
nElems++; // increment size
}
//--------------------------------------------------------------
public int size() // return number of items
{ return nElems; }

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

//--------------------------------------------------------------
public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left - 1; // right of first elem
int rightPtr = right + 1; // left of pivot
while(true)
{
while(leftPtr < right && // find bigger item
theArray[++leftPtr] < pivot)
; // (nop)

while(rightPtr > left && // find smaller item
theArray[--rightPtr] > pivot)
; // (nop)
if(leftPtr >= rightPtr) // if pointers cross,
break; // partition done
else // not crossed, so
swap(leftPtr, rightPtr); // swap elements
} // end while(true)
return leftPtr; // return partition
} // end partitionIt()
//--------------------------------------------------------------

public void swap(int dex1, int dex2) // swap two elements
{
long temp;
temp = theArray[dex1]; // A into temp
theArray[dex1] = theArray[dex2]; // B into A
theArray[dex2] = temp; // temp into B
} // end swap()
//--------------------------------------------------------------
} // end class ArrayPar
////////////////////////////////////////////////////////////////
class PartitionApp
{
public static void main(String[] args)
{
int maxSize = 16; // array size
ArrayPar arr; // reference to array
arr = new ArrayPar(maxSize); // create the array
for(int j=0; j<maxSize; j++) // fill array with
{ // random numbers
long n = (int)(java.lang.Math.random()*199);
arr.insert(n);
}
arr.display(); // display unsorted array
long pivot = 99; // pivot value
System.out.print("Pivot is " + pivot);
int size = arr.size();
// partition array
int partDex = arr.partitionIt(0, size-1, pivot);
System.out.println(", Partition is at index " + partDex);
arr.display(); // display partitioned array
} // end main()
} // end class PartitionApp
////////////////////////////////////////////////////////////////

Solutions

Expert Solution

Java Program:

class ArrayPar
{
    private long[] theArray; // ref to array theArray private
     int nElems; // number of data items

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

public void insert(long value) // put element into array
    {
        theArray[nElems] = value; // insert it
        nElems++; // increment size
    } 
    public int size() // return number of items
     { return nElems; }

public void display() // displays array contents
    {
        System.out.print("A=");
        for(int j=0; j<nElems; j++) // for each element,
            System.out.print(theArray[j] + " "); // display it System.out.println(“”);
    }
    
    public int partitionIt(int left, int right, long pivot)
    {
        int leftPtr = left - 1;
        int rightPtr = right;
        if(rightPtr - leftPtr <= 0)
        {
            System.out.println("\nSub-array too small to sort");
            return -1;
        }
         pivot = theArray[right];
        System.out.println("\nPivot = " + pivot);


        while(true)
        {
            while(leftPtr < right && theArray[++leftPtr] < pivot)
                ; //nop
            while(rightPtr > left && theArray[--rightPtr] > pivot)
                ; //nop
            if(leftPtr >= rightPtr) break;
            else swap(leftPtr, rightPtr);
        }
        swap(leftPtr, right); //move pivot to partition
        return leftPtr;
    } // end partitionIt() 
    public void swap(int dex1, int dex2) // swap two elements
     {
    long temp;
    temp = theArray[dex1]; theArray[dex1] = theArray[dex2]; theArray[dex2] = temp;
// A into temp // B into A
// temp into B
} // end swap() 
} // end class ArrayPar

class PartitionApp {
    public static void main(String[] args) {
        int maxSize = 16;
        ArrayPar arr;
        arr = new ArrayPar(maxSize);
        for (int j = 0; j < maxSize; j++) {

// array size
// reference to array // create the array
// fill array with
// random numbers
            long n = (int) (java.lang.Math.random() * 199);
            arr.insert(n);
        }
        arr.display(); // display unsorted array
        long pivot = 99; // pivot value System.out.print(“Pivot is “ + pivot);
        int size = arr.size();
// partition array
        int partDex = arr.partitionIt(0, size - 1, pivot);
        System.out.println("\nPartition is at index " + partDex);
        arr.display(); // display partitioned array

    }
}// end main()

//output


Related Solutions

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...
Modify the GreenvilleRevenue program so that it uses the Contestant class and performs the following tasks:...
Modify the GreenvilleRevenue program so that it uses the Contestant class and performs the following tasks: The program prompts the user for the number of contestants in this year’s competition; the number must be between 0 and 30. The program continues to prompt the user until a valid value is entered. The expected revenue is calculated and displayed. The revenue is $25 per contestant. For example if there were 3 contestants, the expected revenue would be displayed as: Revenue expected...
Finish the following java question:  Modify a Encryption program so that it uses the following encryption algorithm:...
Finish the following java question:  Modify a Encryption program so that it uses the following encryption algorithm: Every letter (both uppercase and lowercase) converted to its successor except z and Z, which are converted to 'a' and 'A' respectively (i.e., a to b, b to c, …, y to z, z to a, A to B, B to C, …, Y to Z, Z to A) Every digit converted to its predecessor except 0, which is converted to 9 (i.e., 9...
Modify the program below so the driver class (Employee10A) uses a polymorphic approach, meaning it should...
Modify the program below so the driver class (Employee10A) uses a polymorphic approach, meaning it should create an array of the superclass (Employee10A) to hold the subclass (HourlyEmployee10A, SalariedEmployee10A, & CommissionEmployee10A) objects, then load the array with the objects you create. Create one object of each subclass. The three subclasses inherited from the abstract superclass print the results using the overridden abstract method. Below is the source code for the driver class: public class EmployeeTest10A { public static void main(String[]...
Modify the Encryption program so that it uses the following encryption algorithm: Every letter (both uppercase...
Modify the Encryption program so that it uses the following encryption algorithm: Every letter (both uppercase and lowercase) converted to its successor except z and Z, which are converted to 'a' and 'A' respectively (i.e., a to b, b to c, …, y to z, z to a, A to B, B to C, …, Y to Z, Z to A) Every digit converted to its predecessor except 0, which is converted to 9 (i.e., 9 to 8, 8 to...
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...
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(); } } }
"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...
You are required to modify the attached simulation program. This program currently uses an array to...
You are required to modify the attached simulation program. This program currently uses an array to implement the queue. You will modify the program so that it uses the STL queue instead. /* This is for CSC 611 class at NSU Computer Science Department This program is a modified C++ version of the C program From the Second Edition Simulation Modeling & Analysis Averill M. Law W. David Kelton */ #include using namespace std; #include #include double time = 0;...
You are required to modify the attached simulation program. This program currently uses an array to...
You are required to modify the attached simulation program. This program currently uses an array to implement the queue. You will modify the program so that it uses the STL queue instead. #include <iostream> using namespace std; #include <math.h> #include<fstream> double time = 0; int seed = 1; /* External definitions for single-server queeing system. */ const int Q_LIMIT = 100000; /* Limit on queue length. */ const int BUSY = 1; /* Mnemonics for server's being busy */ const...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT