Question

In: Computer Science

IN JAVA Implement Quicksort with ‘median-of-three’ partitioning You should be able to test a 1000, 10000...

IN JAVA

Implement Quicksort with ‘median-of-three’ partitioning

You should be able to test a 1000, 10000 and 10000 length array with inters spanning from 1 to 10,000.

You cannot use functions from standard libraries implementing Quicksort.

Solutions

Expert Solution

The solution is in the code snippet below

// ArrayIns.java
// demonstrates quick sort with median-of-three partitioning
////////////////////////////////////////////////////////////////

import java.util.Scanner; 

public class ArrayIns
{
      private int[] theArray;          // ref to array theArray
      private int nElems;               // number of data items
//--------------------------------------------------------------
   public ArrayIns(int max)          // constructor
   {
      theArray = new int[max];      // create the array
      nElems = 0;                    // no items yet
   }
//--------------------------------------------------------------
   public void insert(int value)    // put element into array
   {
      theArray[nElems] = value;      // insert it
      nElems++;                      // increment size
   }
//--------------------------------------------------------------
   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("");
      System.out.println("");
   }
//--------------------------------------------------------------
   public void quickSort()
   {
      recQuickSort(0, nElems-1);
   }
//--------------------------------------------------------------
   public void recQuickSort(int left, int right)
   {
      int size = right-left+1;
      if(size <= 3)                  // manual sort if small
         manualSort(left, right);
      else                           // quicksort if large
      {
         long median = medianOf3(left, right);
         int partition = partitionIt(left, right, median);
         recQuickSort(left, partition-1);
         recQuickSort(partition+1, right);
      }
    }  // end recQuickSort()
//--------------------------------------------------------------
   public long medianOf3(int left, int right)
   {
      int center = (left+right)/2;
                                         // order left & center
      if( theArray[left] > theArray[center] )
         swap(left, center);
                                         // order left & right
      if( theArray[left] > theArray[right] )
         swap(left, right);
                                         // order center & right
      if( theArray[center] > theArray[right] )
         swap(center, right);

      swap(center, right-1);             // put pivot on right
      return theArray[right-1];          // return median value
    }  // end medianOf3()
//--------------------------------------------------------------
   public void swap(int dex1, int dex2)  // swap two elements
   {
      int temp = theArray[dex1];        // A into temp
      theArray[dex1] = theArray[dex2];   // B into A
      theArray[dex2] = temp;             // temp into B
   }  // end swap()
//--------------------------------------------------------------
    public int partitionIt(int left, int right, long pivot)
    {
       int leftPtr = left;             // right of first elem
       int rightPtr = right - 1;       // left of pivot

       while(true)
       {
          while( theArray[++leftPtr] < pivot )  // find bigger
             ;                                  //    (nop)
          while( theArray[--rightPtr] > pivot ) // find smaller
             ;                                  //    (nop)
          if(leftPtr >= rightPtr)      // if pointers cross,
             break;                    //    partition done
          else                         // not crossed, so
             swap(leftPtr, rightPtr);  // swap elements
       }  // end while(true)
       swap(leftPtr, right-1);         // restore pivot
       return leftPtr;                 // return pivot location
    }  // end partitionIt()
//--------------------------------------------------------------
   public void manualSort(int left, int right)
   {
      int size = right-left+1;
      if(size <= 1)
         return;         // no sort necessary
      if(size == 2)
      {               // 2-sort left and right
         if( theArray[left] > theArray[right] )
            swap(left, right);
         return;
      }
      else               // size is 3
      {               // 3-sort left, center, & right
         if( theArray[left] > theArray[right-1] )
            swap(left, right-1);                // left, center
         if( theArray[left] > theArray[right] )
            swap(left, right);                  // left, right
         if( theArray[right-1] > theArray[right] )
            swap(right-1, right);               // center, right
      }
    }  // end manualSort()
//--------------------------------------------------------------
    public static void main(String[] args) throws java.lang.Exception
    {
      int maxSize = 0;              // array size
      ArrayIns arr;                 // reference to array
      // Declare the object and initialize with 
      // predefined standard input object 
      Scanner sc = new Scanner(System.in);
      
      System.out.println("Enter The size of the array: ");
      System.out.println("");
      maxSize = sc.nextInt();
      
      arr = new ArrayIns(maxSize);  // create the array

      for(int j=0; j<maxSize; j++)  // fill array with
      {                          // random numbers from 1 to 10,000
         int n = (int)(java.lang.Math.random()*10001);
         arr.insert(n);
      }
      System.out.println("The contents before sorting  ");
      arr.display();                // display items
      arr.quickSort();              // quicksort them
      System.out.println("The contents after sorting  ");
      arr.display();                // display them again
    }  // end main()
}  // end class ArrayIns
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////

The output screenshot

For sample I have taken input size to be 20 and the numbers filled in the array are randomly generated


Related Solutions

Implement Quicksort in Java by sorting in parallel after partitioning; for this, the parent thread can...
Implement Quicksort in Java by sorting in parallel after partitioning; for this, the parent thread can continue sorting one segment and a child thread is created for sorting the other segment. However, create a new thread only if both segments contain more than S elements, otherwise sort sequentially both segments. %%writefile Quicksort.java import java.util.Random; YOUR CODE HERE public class Quicksort { static int N; // number of elements to be sorted static int S; // threshold for creating a sub-thread...
implement c++ Quicksort using median of 3 as pivot. this also pass comparator as a function...
implement c++ Quicksort using median of 3 as pivot. this also pass comparator as a function param so it can sort vector in increasing or decreasing order based on the comparator passed. the test code uses std::less comparator. #ifndef QSORT_H #define QSORT_H #include #include using namespace std; template T median_of_three(T& a, T& b, T& c, TComparator comparator) { } template size_t partition(vector& vec, TComparator& comparator, size_t low, size_t high) { // TODO: implement. } template void QuickSort(vector& vec, TComparator comparator,size_t...
Can someone implement the following in Java? Quicksort with switching to Insertion sort when the number...
Can someone implement the following in Java? Quicksort with switching to Insertion sort when the number of elements in the subarray is less than or equal to 2% of the original number Requirements: 1) functions from standard libraries implementing Quicksort are NOT allowed;
implement c++ Quicksort using median of 3 #ifndef QSORT_H #define QSORT_H #include #include using namespace std;...
implement c++ Quicksort using median of 3 #ifndef QSORT_H #define QSORT_H #include #include using namespace std; template T median_of_three(T& a, T& b, T& c, TComparator comparator) { } template size_t partition(vector& vec, TComparator& comparator, size_t low, size_t high) { // TODO: implement. } template void QuickSort(vector& vec, TComparator comparator,size_t low,size_t high) { if(comparator(low,high)){ size_t loc = partition(vec,comparator,low,high); QuickSort(vec,comparator,low,loc-1); QuickSort(vec,comparator,loc+1,high); } return; } template void quicksort(vector& vec, TComparator comparator) { // TODO: implement. size_t size = vec.size(); QuickSort(vec,comparator,0,size-1); } #endif test_case:...
you own three stocks : 1000 shares of apple computer, 10000 shares of cisco system, and...
you own three stocks : 1000 shares of apple computer, 10000 shares of cisco system, and 5000 shares of goldman Sachs group. the current share prices and expected returns of apple,cisco and goldman are respectively $125,$19, $120 and 12%,10%,10.5%. a. what arethe portfolio weights of the three stocks in your portfolio? b. whats the expected return of your portfolio? c. assume that both apple and cisco go up by $5 and goldman goes down by 10$ what are the new...
You own three​ stocks: 1000 shares of Apple​ Computer, 10000 shares of Cisco​ Systems, and 5000...
You own three​ stocks: 1000 shares of Apple​ Computer, 10000 shares of Cisco​ Systems, and 5000 shares of Goldman Sachs. The current share prices and expected returns of​ Apple, Cisco, and Goldman Sachs​ are, respectively, $ 156​, $ 23​, $ 129 and 12 %​, 10 %​, 10.5 %. a. What are the portfolio weights of the three stocks in your​ portfolio? b. What is the expected return of your​ portfolio? c. Suppose the price of Apple stock goes up by...
Must be written in Java: After completing this lab, you should be able to: Write a...
Must be written in Java: After completing this lab, you should be able to: Write a Java class to represent Time. Create default and parameterized constructors. Create accessor and mutator methods. Write a toString method. This project will represent time in hours, minutes, and seconds. Part 1: Create a new Java class named Time that has the following instance fields in the parameterized constructor: hours minutes seconds Create a default constructor that sets the time to that would represent the...
Implement and test a TaskList application in Java that will allow a client to manage information...
Implement and test a TaskList application in Java that will allow a client to manage information about daily tasks.  A task has a task name, is scheduled on a specific day of the week and can have a comment attached to it. Together, the task name and day uniquely identify a task. There may be tasks with the same name scheduled for different days of the week. The application should allow the client to start with an empty TaskList and then...
Java ProgrammingAssignment 4.1Create an interactive (the user should be able to input thevalues)...
Java ProgrammingAssignment 4.1Create an interactive (the user should be able to input the values) Java Application to process your utility bill for at-least 6 months. Use Class-Object methodology and use single dimensional arraysin your application. Write detailed comments in your program. You should have a two classes (for example, MontlyBill.java & MontlyBillTest.java)..Hint: Use the program (GradeBook) in Fig 7.14 & 7.15(GradeBookTest) as a building template.Assignment 4.2Use the same program that you have created in 4.1, and use “two dimensional array”....
1) You must implement a recursive Quicksort algorithm that will read integers from the attached MyList.txt...
1) You must implement a recursive Quicksort algorithm that will read integers from the attached MyList.txt file. Your algorithm must sort the list(integers)in ascending order. 2)You must implement a recursive Mergesort algorithm that will read integers from the attached MyList.txt file. Your algorithm must sort the list(integers)in ascending order. My List.txt Values 7 3 4 1 4 4 9 9 4 8 4 5 3 9 2 3 7 0 6 4 4 5 0 1 9 2 1 7...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT