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...
(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); }
Create a new Java program named AllAboutMe (For JAVA we use blue J) Write code to...
Create a new Java program named AllAboutMe (For JAVA we use blue J) Write code to have the program print your name, favorite color, and three hobbies to a new text file called “AllAboutMe” using PrintStream. Submit code.
Assignment Content Resource: ****************************CODE PASTED BELOW******************************* For this assignment, you will develop Java™ code that relies...
Assignment Content Resource: ****************************CODE PASTED BELOW******************************* For this assignment, you will develop Java™ code that relies on localization to format currencies and dates. In NetBeans, copy the linked code to a file named "Startercode.java". Read through the code carefully and replace all occurrences of "___?___" with Java™ code. Note: Refer to "Working with Dates and Times" in Ch. 5, "Dates, Strings, and Localization," in OCP: Oracle® Certified Professional Java® SE 8 Programmer II Study Guide for help. Run and debug...
Assignment Purpose Write a well commented java program that demonstrates the use and re-use of methods...
Assignment Purpose Write a well commented java program that demonstrates the use and re-use of methods with input validation. Instructions It is quite interesting that most of us are likely to be able to read and comprehend words, even if the alphabets of these words are scrambled (two of them) given the fact that the first and last alphabets remain the same. For example, “I dn'ot gvie a dman for a man taht can olny sepll a wrod one way.”...
This is a programming assignment!!! Start with the Assignment3.java source code posted to Canvas. This code...
This is a programming assignment!!! Start with the Assignment3.java source code posted to Canvas. This code outputs the programmer’s name , prompts the user to enter two numbers (integers) and outputs their sum. Note: When you run the program, it expects you to enter two integer values (a counting or whole number like 1, 216, -35, or 0) Make the following changes/additions to the code: On line 11, change the String myName from “your full name goes here!!!” to your...
NEED TO REWRITE THIS IN OOP MODE ######## HOMEWORK 19 ###### Rewrite the code in the...
NEED TO REWRITE THIS IN OOP MODE ######## HOMEWORK 19 ###### Rewrite the code in the OOP mode (class mode). ########################### lambda trick ##### first: changing label properties: after you've created a label, you ##### may want to change something about it. To do that, use configure method: ## label.configure(text = 'Yes') ## label.configure(bg = 'white', fg = 'black') ### that change the properties of a label called label. ################################################### ## from tkinter import * abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def callback(x):...
Write Java code for each of the following problem a. Two players, a and b, try...
Write Java code for each of the following problem a. Two players, a and b, try to guess the cost of an item. Whoever gets closest to the price without going over is the winner. Return the value of the best bid. If both players guessed too high, return -1. example: closestGuess(97, 91, 100) → 97 closestGuess(3, 51, 50) → 3 closestGuess(12, 11, 10) → -1 b. Given a non-empty string, return true if at least half of the characters...
Write a java code that ask users to pick two of the job categories and enter...
Write a java code that ask users to pick two of the job categories and enter two working areas from each category. The users must enter the start and end time for each of the two selection and calculate the hours for each category and the total hours for all the categories. If the users total hours is more that 10 hours, they are awesome, if not, they are lazy. Shor and simple code using while or for loops. Thanks...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT