Question

In: Computer Science

USE GENERICS TO WRITE THE JAVA CODE FOR THIS ASSIGNMENT In this assignment, rewrite two of...

USE GENERICS TO WRITE THE JAVA CODE FOR THIS ASSIGNMENT

In this assignment, rewrite two of the following sorting methods (Insertion Sort, Selection Sort, Quick Sort, and Merge Sort) to sort ArrayList of objects using Comaprable interface. (60 points)

Solutions

Expert Solution


// Java program to create methods for sorting generic arraylist data

import java.util.ArrayList;
import java.util.Random;
public class GenericSorting {
  
   // generic method that partitions the given arraylist and returns the location of the pivot
   public static <T extends Comparable<T>> int partition(ArrayList<T> data,int low, int high)
   {
       int mid = (low+high)/2; // mid element is selected as the pivot
       swap(data,low,mid);
       int pivotkey = low;
       T pivot = data.get(low);
       for(int i=low+1;i<=high;i++)
       {
           if(data.get(i).compareTo(pivot) < 0)
               swap(data,i,++pivotkey);
       }
       swap(data,low,pivotkey);
       return pivotkey;
   }
  
   // generic method to implement quicksort on the given arraylist
   public static <T extends Comparable<T>> void quickSort(ArrayList<T> data,int low,int high)
   {
       int pivotkey;
       if(low<high)
       {
           pivotkey = partition(data,low,high);
           quickSort(data,low,pivotkey-1);
           quickSort(data,pivotkey+1,high);
       }
   }
  
   // generic method to swap the values at index1 and index2 of data arraylist
   public static <T> void swap(ArrayList<T> data, int index1, int index2) {
T temp = data.get(index1);
data.set(index1, data.get(index2));
data.set(index2,temp);
}
  
  
   // generic method to sort a given arraylist using mergesort
   public static <T extends Comparable<T>> void mergeSort(ArrayList<T> arr,int low,int high)
   {
       int mid;
       if(low<high)
       {  
          
           mid = (low+high)/2;
           mergeSort(arr,low,mid);
           mergeSort(arr,mid+1,high);
           mergeArr(arr,low,high,mid);
       }
   }
  
   // generic method to merge with sorted arraylist
   public static <T extends Comparable<T>> void mergeArr(ArrayList<T> arr,int low,int high,int mid)
   {
       int l = low;
       int h = mid+1;
       int i=low;
       T brr[] = (T[])new Comparable[arr.size()];      
       while(l<=mid && h<=high)
       {
           if(arr.get(l).compareTo(arr.get(h)) < 0)
           {
               brr[i] = arr.get(l);
               l++;
           }else
           {
               brr[i]=arr.get(h);
               h++;
           }
           i++;
       }
      
       while(l<=mid)
       {
           brr[i] = arr.get(l);
           i++;
           l++;
       }
      
       while(h<=high)
       {
           brr[i] = arr.get(h);
           i++;
           h++;
       }
  
       for(i=low;i<=high;i++)
       {
           arr.set(i, brr[i]);
       }
      
   }
  
   // generic method to sort a given arraylist using selection sort
   public static <T extends Comparable<T>> void selectionSort(ArrayList<T> arr)
   {
       int minIndex;
       for(int i=0;i<arr.size()-1;i++)
       {
           minIndex = i;
           for(int j=i+1;j<arr.size();j++)
           {
               if(arr.get(j).compareTo(arr.get(minIndex)) < 0)
                   minIndex = j;
           }
          
           if(i != minIndex)
           {
               T temp = arr.get(minIndex);
               arr.set(minIndex, arr.get(i));
               arr.set(i, temp);
           }
       }
   }
  
   // generic method to sort a given arraylist using insertionsort
   public static <T extends Comparable<T>> void insertionSort(ArrayList<T> arr)
   {
       int i,j;
       T key;
       for(i=1;i<arr.size();i++)
       {
           j=i-1;
           key = arr.get(i);
          
           while((j >=0) && (arr.get(j).compareTo(key) > 0) )
           {
               arr.set(j+1, arr.get(j));
               j--;
           }
          
           arr.set(j+1, key);
       }
   }
  
   public static void main(String[] args) {
       // test the quick sort, merge sort, selection sort and insertion sort methods
       ArrayList<Integer> quickData, mergeData, selectionData, insertData;
       quickData = new ArrayList<Integer>();
       mergeData = new ArrayList<Integer>();
       selectionData = new ArrayList<Integer>();
       insertData = new ArrayList<Integer>();
      
       Random ran = new Random();
       for(int i=0;i<10;i++)
       {
           int n = ran.nextInt(100);
           quickData.add(n);
           mergeData.add(n);
           selectionData.add(n);
           insertData.add(n);
       }
      
       System.out.println("Quick Sort Testing: ");
       System.out.println("Before : "+quickData.toString());
       quickSort(quickData,0,quickData.size()-1);
       System.out.println("After : "+quickData.toString());
      
      
       System.out.println("Merge Sort Testing: ");
       System.out.println("Before : "+mergeData.toString());
       mergeSort(mergeData,0,mergeData.size()-1);
       System.out.println("After : "+mergeData.toString());
      
       System.out.println("Insertion Sort Testing: ");
       System.out.println("Before : "+insertData.toString());
       insertionSort(insertData);
       System.out.println("After : "+insertData.toString());
      
       System.out.println("Selection Sort Testing: ");
       System.out.println("Before : "+selectionData.toString());
       selectionSort(selectionData);
       System.out.println("After : "+selectionData.toString());
   }
}
//end of program

Output:


Related Solutions

Write a small Java class called StoreAddStuff that uses generics to store two variables of type...
Write a small Java class called StoreAddStuff that uses generics to store two variables of type T passed in during construction, then returns their sum through a non-static method.
Language for this question is Java write the code for the given assignment Given an n...
Language for this question is Java write the code for the given assignment Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the matrix. Then the next line contains the n x n elements...
PLEASE CODE IN JAVA In this assignment you will write a program in that can figure...
PLEASE CODE IN JAVA In this assignment you will write a program in that can figure out a number chosen by a human user. The human user will think of a number between 1 and 100. The program will make guesses and the user will tell the program to guess higher or lower.                                                                   Requirements The purpose of the assignment is to practice writing functions. Although it would be possible to write the entire program in the main function, your...
Use Java to rewrite the following pseudo-code segment using a loop structure without goto, break, or...
Use Java to rewrite the following pseudo-code segment using a loop structure without goto, break, or any other unconditional branching statement: k = (j+13)/27; //assume i,j,k are integers properly declared. loop: if k > 10 then goto out k=k+1.2; i=3*k-1; goto loop; out: …
Java Programming Preferably Concepts: Generics Arrays Objects Part I: Write a routine in Java that takes...
Java Programming Preferably Concepts: Generics Arrays Objects Part I: Write a routine in Java that takes an array, the length of the array, and an element and returns the position of the element in the array. For example, given the array with values [2, 4, 6, 8] and element 6, the routine should return 2 (since counting from 0, 6 occurs at position 2 in the array). Your routine should use generics to enable your routine to be reusable for...
(This is for java) I need to rewrite this code that uses a while loop. public...
(This is for java) I need to rewrite this code that uses a while loop. public class Practice6 {      public static void main (String [] args) {         int sum = 2, i=2;        do { sum *= 6;    i++;    } while (i < 20); System.out.println("Total is: " + sum); }
Write a program to multiply two polynomials. Code needed in Java.
Write a program to multiply two polynomials. Code needed in Java.
Write a java code that could be used to show the simulation of a tornado. use...
Write a java code that could be used to show the simulation of a tornado. use the understanding of the mix of low temperature and high temperature wind go create a spinning vortex. ***POSTED INCORRECT QUESTION** here is the real question: plz write a simple java code to show a spinning circle of particles.
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite...
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite the code implementing a template class using a linked list instead of an array. Note: The functionality should remain the same *************************************************************************************************************** /** * Stack implementation using array in C/procedural language. */ #include <iostream> #include <cstdio> #include <cstdlib> //#include <climits> // For INT_MIN #define SIZE 100 using namespace std; /// Create a stack with capacity of 100 elements int stack[SIZE]; /// Initially stack is...
Write a complete Java code that contain two classes. A GradeBook and a GradeBookTester. - The...
Write a complete Java code that contain two classes. A GradeBook and a GradeBookTester. - The GradeBook class contains the followings: - An array of grades (integer array) declared as a field. - A constructor that takes an integer value as parameter (len), and creates the grades array of size equals to len. - A method called fillArray that fills the grades array with random integers. Acceptable values are between 1 and 100 (inclusive) - A method called printStatistics that...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT