Question

In: Computer Science

9. Modify the quicksort and mergesort programs we learnt during the class to count the number...

9. Modify the quicksort and mergesort programs we learnt during the class to count the number of element comparisons for the two sorting methods. Use the following test drive to test them.

public class Sorts

{

   int numComparisions = 0;

   public void quicksort(int [] x, int l, int h)

   {

// your modifies codes go here

   }

   public void mergesort(int [] x, int l, int h)

   {

// your modifies codes go here

   }

   public static void main(String [] args)

   {

Sorts sorts = new Sorts();

int N = 10000;

int [] x = new int[N];

int [] y = new int[N];

for (int n=0; n < N; n++)

x[n]=y[n] = (int)(Math.random()*N*2);

sorts.quicksort(x,0,x.length-1);

System.out.println("Quicksort:#C="+ sorts.numComparisons);

sorts.numComparisons = 0;

sorts.quicksort(y,0,y.length-1);

System.out.println("Mergesort:#C="+ sorts.numComparisons);

   }

}

10. Modify your program above to count and print out how many times of recursive calls have

been made during the sorting.

Solutions

Expert Solution

Merge Sort program with count of comparisons and recursive calls:

class Main {
    public static int count_comparison = 0, count_calls = 0;
        // Merges two subarrays of arr[].
        // First subarray is arr[l..m]
        // Second subarray is arr[m+1..r]
        void merge(int arr[], int l, int m, int r)
        {
                // Find sizes of two subarrays to be merged
                int n1 = m - l + 1;
                int n2 = r - m;

                /* Create temp arrays */
                int L[] = new int[n1];
                int R[] = new int[n2];

                /*Copy data to temp arrays*/
                for (int i = 0; i < n1; ++i)
                        L[i] = arr[l + i];
                for (int j = 0; j < n2; ++j)
                        R[j] = arr[m + 1 + j];

                /* Merge the temp arrays */

                // Initial indexes of first and second subarrays
                int i = 0, j = 0;

                // Initial index of merged subarry array
                int k = l;
                while (i < n1 && j < n2) {
                        if (L[i] <= R[j]) {
                            count_comparison += 1;
                                arr[k] = L[i];
                                i++;
                        }
                        else {
                                arr[k] = R[j];
                                j++;
                        }
                        k++;
                }

                /* Copy remaining elements of L[] if any */
                while (i < n1) {
                        arr[k] = L[i];
                        i++;
                        k++;
                }

                /* Copy remaining elements of R[] if any */
                while (j < n2) {
                        arr[k] = R[j];
                        j++;
                        k++;
                }
        }

        // Main function that sorts arr[l..r] using
        // merge()
        void sort(int arr[], int l, int r)
        {
                if (l < r) {
                        // Find the middle point
                        int m = (l + r) / 2;

                        // Sort first and second halves
                        sort(arr, l, m);
                        count_calls += 1; 
                        sort(arr, m + 1, r);
                        count_calls += 1; 

                        // Merge the sorted halves
                        merge(arr, l, m, r);
                }
        }

        /* A utility function to print array of size n */
        static void printArray(int arr[])
        {
                int n = arr.length;
                for (int i = 0; i < n; ++i)
                        System.out.print(arr[i] + " ");
                System.out.println();
        }

        // Driver method
        public static void main(String args[])
        {
                int N = 10000;
                int [] x = new int[N];
                int [] y = new int[N];
                
                for (int n=0; n < N; n++)
                {
                    x[n]=y[n] = (int)(Math.random()*N*2);
                } 

                System.out.println("Given Array");
                printArray(x);

                Main ob = new Main();
                ob.sort(x, 0, x.length - 1);

                System.out.println("\nSorted array");
                printArray(x);
                System.out.println("\nNumber of comparison are:" + count_comparison);
                System.out.println("\nNumber of recursive calls are:" + count_calls);
                
        }
}


Quick Sort program with count of comparisons and recursive calls:

class Main 
{ 
    public static int count_comparisons = 0, count_calls = 0;   //  variables to capture counts
        /* This function takes last element as pivot, 
        places the pivot element at its correct 
        position in sorted array, and places all 
        smaller (smaller than pivot) to left of 
        pivot and all greater elements to right 
        of pivot */
        int partition(int arr[], int low, int high) 
        { 
                int pivot = arr[high]; 
                int i = (low-1); // index of smaller element 
                for (int j=low; j<high; j++) 
                { 
                    count_comparisons += 1;
                        // If current element is smaller than the pivot 
                        if (arr[j] < pivot) 
                        { 
                                i++; 

                                // swap arr[i] and arr[j] 
                                int temp = arr[i]; 
                                arr[i] = arr[j]; 
                                arr[j] = temp; 
                        } 
                } 

                // swap arr[i+1] and arr[high] (or pivot) 
                int temp = arr[i+1]; 
                arr[i+1] = arr[high]; 
                arr[high] = temp; 

                return i+1; 
        } 


        /* The main function that implements QuickSort() 
        arr[] --> Array to be sorted, 
        low --> Starting index, 
        high --> Ending index */
        void sort(int arr[], int low, int high) 
        { 
                if (low < high) 
                { 
                        /* pi is partitioning index, arr[pi] is 
                        now at right place */
                        int pi = partition(arr, low, high); 

                        // Recursively sort elements before 
                        // partition and after partition 
                        sort(arr, low, pi-1); 
                        count_calls += 1;
                        sort(arr, pi+1, high); 
                        count_calls += 1;
                } 
        } 

        /* A utility function to print array of size n */
        static void printArray(int arr[]) 
        { 
                int n = arr.length; 
                for (int i=0; i<n; ++i) 
                        System.out.print(arr[i]+" "); 
                System.out.println(); 
        } 

        // Driver program 
        public static void main(String args[]) 
        { 
            int N = 10000;
                int [] x = new int[N];
                for (int n=0; n < N; n++)
                {
                    x[n] = (int)(Math.random()*N*2);
                } 
                
                System.out.println("Given Array");
                printArray(x);

                Main ob = new Main();
                ob.sort(x, 0, x.length - 1); 
                count_calls += 1;

                System.out.println("sorted array"); 
                printArray(x); 
                
                System.out.println("Number of comparisons :" + count_comparisons); 
                System.out.println("Number of recursive calls :" + count_calls);        
        } 
} 


Related Solutions

Below is the pseudocode for Quicksort and Partition that we talked about in class. As usual...
Below is the pseudocode for Quicksort and Partition that we talked about in class. As usual with recursive functions on arrays, we see the array indices s and e as arguments. Quicksort(A, s, e) sorts the part of the array between s and e inclusively. The initial call (that is, to sort the entire array) is Quicksort(A, 0, n − 1) QuickSort(A, s, e)   if s < e p = Partition (A, s, e) // Partition the array and return...
Modify the following C++ program to count the number of correct and incorrect responses typed by...
Modify the following C++ program to count the number of correct and incorrect responses typed by the student. After the student types 5 answers, your program should calculate the percentage of correct responses. If the percentage is lower than 75 percent, your program should print “Please ask for extra help” and then terminate. If the percentage is 75 percent or higher, your program should print “Good work!” and then terminate. The program is as follows: #include<iostream> #include<iomanip> #include<cstdlib> #include<time.h> using...
Modify the following code to count the number of recursive calls made for the Manhattan-path problem...
Modify the following code to count the number of recursive calls made for the Manhattan-path problem we studied earlier. Next, modify to include stored values and see how that reduces the number of calls made. public class ManhattanWithCallCount { public static void main (String[] argv) { // Test case 1: go from (2,2) to (0,0) int r = 2; int c = 2; int n = countPaths (r, c); System.out.println ("r=" + r + " c=" + c + "...
We are going to derive the average number of moves for quicksort using a somewhatunusual partitioning...
We are going to derive the average number of moves for quicksort using a somewhatunusual partitioning algorithm. We partition on the first element. Take it out. Look for theright most element that is smaller and place it in the first position (which is the newly openedposition on the left side). Look for the left most element that is larger and place it in the newlyopened position on the right side. Starting from there look for the right most element that...
I need to,  Modify my mapper to count the number of occurrences of each character (including punctuation...
I need to,  Modify my mapper to count the number of occurrences of each character (including punctuation marks) in the file. Code below: #!/usr/bin/env python #the above just indicates to use python to intepret this file #This mapper code will input a line of text and output <word, 1> # import sys sys.path.append('.') for line in sys.stdin: line = line.strip() #trim spaces from beginning and end keys = line.split() #split line by space for key in keys: value = 1 print...
Determine the execution count of the following programs: (number of loops executed?) int i = 10;...
Determine the execution count of the following programs: (number of loops executed?) int i = 10; while(i > 0) { for(int p = 5; p < 14; p++) b{ System.out.println(i + p) p++; } i--; }
1. In class we learnt about the broad classifications of financial markets. How will you explain...
1. In class we learnt about the broad classifications of financial markets. How will you explain any three of these classifications to your friends in history department? 2. Why are financial markets so keenly regulated? Explain the rational for the regulation of financial markets in Ghana, providing cogent examples of such regulations within the Ghanaian financial market. 3. Describe the requirements for listing on the Ghana Alternative Exchange (GAX) relative to the first official listing requirements. 4. Expatiate on the...
1. In class we learnt about the broad classifications of financial markets. How will you explain...
1. In class we learnt about the broad classifications of financial markets. How will you explain any three of these classifications to your friends in history department?
here are several access control models and in class we learnt specifically about 3 flavors: Mandatory...
here are several access control models and in class we learnt specifically about 3 flavors: Mandatory Access Control (MAC), Role Based Access Control (RBAC), and Discretionary Access Control (DAC). In your own words differentiate these 3 models. Your answer should include a specific example where a specific model is best.
Complete the coding/testing of the heap sort method we began in class. Then modify your program...
Complete the coding/testing of the heap sort method we began in class. Then modify your program so that it outputs a comparison of the actual number of swaps it performs to the predicted number of swaps, and a comparison of the actual sort effort to the predicted and minimum sort effort. The output should be formatted exactly as shown below. Actual swaps = xxxx; Predicted swaps = xxxx Actual sort effort = xxxx; Predicted sort effort = xxxx; Min sort...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT