Question

In: Computer Science

After running the experiment with the pivot, comment out the line, update the pivot selection to...

After running the experiment with the pivot, comment out the line, update the pivot selection to use the median of the first, middle, and last items, and run the experiment.

What line needs to be commented out and how would I update the pivot selection to use the median?

Example.java

package sorting;

import java.io.IOException;
import java.util.Random;
import sorters.QuickSort;

public class Example {

   public static void main(String args[]) throws IOException {
       int n = 100;   // adjust this to the number of items to sort
       int runs = 11;
      
       
       partB(n, runs);


   public static void partB(int n, int runs) {
       int [] data = new int[n];
       QuickSort quicksort = new QuickSort();
      
       labels(runs);
       for (int i = 0; i < runs; i++) {
           randomArray(data);
           quicksort.sort(data);
       }
       System.out.println();
      
   }
  
   public static void labels(int runs) {
       for(int i = 0; i < runs; i++) {
           String label = "Run " + i;
           System.out.printf("%12s ", label);
       }
       System.out.println();      
   }
  
   public static void randomArray(int [] data) {
       Random rand = new Random();      
       for(int j = 0; j < data.length; j++) {
           data[j] = rand.nextInt();
       }  
   }
  
}

QuickSort.java

package sorters;

// note that this class can only sort primitive ints correctly.

public class QuickSort {
  
   private int[] items;
  
   public void sort(int[] items) {
       this.items = items;
      
       long start = System.nanoTime();
       quicksort(0, items.length-1);
       long finish = System.nanoTime();
       //System.out.println(Arrays.toString(items));
       System.out.printf("%12s ", finish-start);
   }
  
   private int partition(int left, int right) {
       int i = left;
       int j = right;
        int temp;
        int pivot = (int) items[(left + right) / 2];
      
      
        while (i <= j) {
           while((int) items[i] < pivot)
               i++;
            while((int) items[j] > pivot)
                j--;
            if(i <= j) {
                temp = items[i];
                items[i] = items[j];
                items[j] = temp;
                i++;
                j--;
            }
        }
        return i;
   }

   private void quicksort(int left, int right) {

       int index = partition(left, right);

        if(left < index - 1)
           quicksort(left, index-1);
        if(index < right)
            quicksort(index, right);
   }
}

Solutions

Expert Solution

Package -- sorting

class

QuickSort.java

code is changed here in this class file below for calculating median and used a findmedian() function and commnetd previous code of finding partition

Steps to find median:

1) take thr first middle and last element in the last

2) sort the 3 elements (can be done using colections.sort())

3) return the middle element and use it as a pivot

example

for let first element be 5 last be 8 and middle be 3

so element 5,8,3 will be passed

and sorted as 3,5,8

and middle element 5 will be returned called as median used as pivot in algorithm

package sorters;

import java.util.ArrayList;
import java.util.Collections;

// note that this class can only sort primitive ints correctly.

public class QuickSort {
  
   private int[] items;
  
   public void sort(int[] items) {
       this.items = items;
      
       long start = System.nanoTime();
       quicksort(0, items.length-1);
       long finish = System.nanoTime();
       //System.out.println(Arrays.toString(items));
       System.out.printf("%12s ", finish-start);
       
                //FOR CHECKING CORRECT OUTPUT AFTER {YOUR REFERENCE}
                /*
                 * for(int i=0;i<items.length;i++) System.out.print(items[i]+" ");
       System.out.println(); */
   }
  
   //function called inside paertition to find pivot value
   private int findMedian(int a,int b, int c)
   {
           //adding all 3 first last and middle value of arraylist 
           ArrayList<Integer> sortedMedian=new ArrayList<Integer>();
           sortedMedian.add(a);
           sortedMedian.add(b);
           sortedMedian.add(c);
           
           //using collection fucntion sorting items in arraylst
           Collections.sort(sortedMedian);
           
           //return midle value now as there are are 3 elements in list always so middle element will always be 1
           //so returning elemet at 1 index{2nd element}
           return sortedMedian.get(1);
   }
   
   private int partition(int left, int right) {
       int i = left;
       int j = right;
        int temp;
        
        //line to be commented before it was middle
        //int pivot = (int) items[(left + right) / 2];
        
        //now it will be median of first last and middle element
        int pivot = findMedian(items[left], items[(left + right) / 2], items[right]);
      
        while (i <= j) {
           while((int) items[i] < pivot)
               i++;
            while((int) items[j] > pivot)
                j--;
            if(i <= j) {
                temp = items[i];
                items[i] = items[j];
                items[j] = temp;
                i++;
                j--;
            }
        }
        return i;
   }

   private void quicksort(int left, int right) {

       int index = partition(left, right);

        if(left < index - 1)
           quicksort(left, index-1);
        if(index < right)
            quicksort(index, right);
   }
}

Package -- sorters

class

Example.java

package sorting;

import java.io.IOException;
import java.util.Random;
import sorters.QuickSort;

public class Example {

   public static void main(String args[]) throws IOException {
       int n = 100;   // adjust this to the number of items to sort
       
       //set value of n to small to check output for less value for debugging
       int runs = 11;
      
       
       partB(n, runs);
   }


   public static void partB(int n, int runs) {
       int [] data = new int[n];
       QuickSort quicksort = new QuickSort();
      
       labels(runs);
       for (int i = 0; i < runs; i++) 
       {
           randomArray(data);
           
                        //FOR CHECKING CORRECT OUTPUT BEFORE {YOUR REFERENCE}
           /*
                         * for(int k=0;k<data.length;k++) System.out.print(data[k]+" ");
                         * System.out.println();
                         */
           
           quicksort.sort(data);
       }
       System.out.println();
      
   }
  
   public static void labels(int runs) {
       for(int i = 0; i < runs; i++) {
           String label = "Run " + i;
           System.out.printf("%12s ", label);
       }
       System.out.println();      
   }
  
   public static void randomArray(int [] data) {
       Random rand = new Random();      
       for(int j = 0; j < data.length; j++) {
           data[j] = rand.nextInt(10);
       }  
   }
  
}

code is well commented for your better understanding

Note: I have also written code to print array values before and after sorting in comments so that you can check validity of median quick sorting answer and also set value of 'n' less like 5 for better readability of output

Output screenshot:

Output screenshot (VALIDATING INPUT/OUTPUT BY Priting array before and after):

here note only input and output and not format of printing

Hope you are able to understand all concepts easily and Please rate the answer


Related Solutions

After Carrying out the Aspirin synthesis experiment, Suggest an experiment or technique based on what you...
After Carrying out the Aspirin synthesis experiment, Suggest an experiment or technique based on what you have learned in the last few weeks to confirm the preparation of Aspirin. (Give full details) Hint: You are provided with pure sample of Aspirin  
A student is running an experiment in which 73.4 grams of BaI2 is needed, but the...
A student is running an experiment in which 73.4 grams of BaI2 is needed, but the only jar of reagent in the lab is labelled barium iodide dihydrate. How many grams of the hydrate must the student weigh out in order to get the desired amount of the anhydrous compound? 1. How many GRAMS of potassium are present in 1.73 grams of potassium chromate, K2CrO4 ? grams potassium. How many GRAMS of potassium chromate can be made from 2.35 grams...
You walk into a room and notice that there someone is running an experiment involving a...
You walk into a room and notice that there someone is running an experiment involving a spring-mass system. You have no idea when the experiment started, but observe that the mass attached to the spring is oscillating with period 3 (seconds) and that the amplitude of the oscillations remain constant (to your naked eye) while you are in the room. What are two differential equations which model the motion of the mass? One system must be inhomogeneous and the other...
Suppose that a software development team released an update to one of their mobile applications after...
Suppose that a software development team released an update to one of their mobile applications after receiving complaints about the previous version from 9.4% of their customers. A few weeks after the update was released, the development team wanted to know if fewer customers had complaints. The team selected a random sample of 325 customers and found that 21 of them submitted complaints about the application after the update was released. The team wants to use a one‑sample  z ‑test for...
1.     After completing your mutagenesis experiment you set out to determine which gene was responsible. To do...
1.     After completing your mutagenesis experiment you set out to determine which gene was responsible. To do so you sequenced the DNA of 100 mutant worms. Listed below is the sequence of a portion of chromosome 1 for 10 of these worms. Circle the nucleotide that is the likely causative mutation for the mutant phenotype. WILDTYPY SEQUENCE: 5’ AACTCCCTTCTTGGACTACCAGACCTGGGATCCTCTAGCATTCAAGGCT 3’   5’ AACTGCCATCATGGACTACCTGACCTGCGAACCTCTAGCATTCAAGGCT 3’   5’ AACTGCCATCTTCGACTACATGACCAGCCAACCTCTAGCATTCAAGGCT 3’   5’ AACTCCCATCTTGGATTACCTGACCTGCGAACCTCTAGCATTCAAGGCT 3’   5’ AACTCCCATCTTGGACTACCTGACCTGCGAACCTCTAGCATTCAAGGCT 3’   5’ AACTCCCATCTTGGACTACCTGACCTGCGAACCTCTAGCATTCAAGGCT 3’   5’ AATTGCCAACTTGGTCTAGCTGACCTGCAAACTCTAGCATACAAGGCT 3’   5’ AACTGCCATCTTGGACTACCTCACCTGCGATCCTCTAGCAATCAAGGCT 3’  ...
A production line manager wants to determine how well the production line is running. He randomly...
A production line manager wants to determine how well the production line is running. He randomly selected 90 items off of the assembly line and found that 8 were defective. (Assume all conditions have been satisfied for building a confidence interval). Find the 99% confidence interval. (0.0234, 0.1099) (0.0116, 0.1662) (0.0301, 0.1477) (0.0396, 0.1382)
Lactate concentration in the blood rises rapidly during hard running. After running, the blood concentration drops...
Lactate concentration in the blood rises rapidly during hard running. After running, the blood concentration drops slowly. Describe why the lactate concentration increases and why it decreases.
In a simple experiment, you are going out there to the duck pond to seine out...
In a simple experiment, you are going out there to the duck pond to seine out one redbreast sunfish at random, determine its sex, and put it back in the pond and then, after 30 minutes, repeat this process. Assuming that the sex ratio for redbreast in the pond is 1:1, develop and plot the pmf of the random variable X, defined as the number of females in the two fish observed. Is the distribution of X symmetric or asymmetric?...
You’re running an experiment to determine whether students perform better if they are rewarded with candy...
You’re running an experiment to determine whether students perform better if they are rewarded with candy or vegetables. You sample 5 students from your class and you first reward the students with vegetables when they get right answers in the class. Then you test them and record their scores. Next, with a different 5 students you reward these students with cookies when they get right answers in the class. Then you test them with another test and record their scores....
A researcher is running an experiment on the effectiveness of three different energy drinks. She randomly...
A researcher is running an experiment on the effectiveness of three different energy drinks. She randomly selects 150 individuals from the population and evenly splits them into three groups, each which consumes a different energy drink. 1. The research/alternative hypothesis for this test is that at least one of the three groups will be different. True or False? The statistical results of the test are as follows: F(2, 147) = 2.24, p > .05. 2. In the above results, degrees...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT