Question

23.8 (Generic insertion sort) Write the following two generic methods using insertion sort. The first method...

23.8 (Generic insertion sort) Write the following two generic methods using insertion sort. The first method sorts the elements using the Comparable interface, and the second uses the Comparator interface.(Use Java program)
public static > void insertionSort(E[] list)

public static void insertionSort(E[] list, Comparator comparator)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

EDIT: created a class called IntegerComparator that implements Comparator interface and implemented compare() method. Inside main() of Test class, sorted the array using insertionSort method, passing an object of IntegerComparator as Comparator.

// Test.java

import java.util.Collections;

import java.util.Comparator;

public class Test {

      /**

      * required method to sort an array using natural order (based on compareTo

      * value defined in type E.) Since we need to use compareTo method, we have

      * to add constraints to the type parameter E to be subclasses of Comparable

      * interface. i.e only those objects that implement comparable interface can

      * be passed to this method

      *

      * @param array

      *            array to be sorted

      */

      public static <E extends Comparable<E>> void insertionSort(E[] array) {

            int i, j;

            E key;

            // looping from i=1 to i=n-1

            for (i = 1; i < array.length; i++) {

                  // taking element at index i as key value

                  key = array[i];

                  // previous index

                  j = i - 1;

                  // looping through each previous element, shifting each value

                  // greater than key to one place right. at any point if the key is

                  // smaller than or equal to any element, the inner loop will stop.

                  while (j >= 0 && array[j].compareTo(key) > 0) {

                        // storing element at j in j+1

                        array[j + 1] = array[j];

                        j--;

                  }

                  // now inserting key at proper position. after this line, the

                  // elements upto index i will be in sorted order.

                  array[j + 1] = key;

            }

      }

      /**

      * method to sort the array using a given comparator.

      *

      * @param array

      *            array to be sorted

      * @param comparator

      *            comparator to be used

      */

      public static <E> void insertionSort(E[] array, Comparator<E> comparator) {

            int i, j;

            E key;

            // looping from i=1 to i=n-1

            for (i = 1; i < array.length; i++) {

                  // taking element at index i as key value

                  key = array[i];

                  // previous index

                  j = i - 1;

                  // looping through each previous element, shifting each value

                  // greater than key to one place right. at any point if the key is

                  // smaller than or equal to any element, the inner loop will stop.

                  while (j >= 0 && comparator.compare(array[j], key) > 0) {

                        // storing element at j in j+1

                        array[j + 1] = array[j];

                        j--;

                  }

                  // now inserting key at proper position. after this line, the

                  // elements upto index i will be in sorted order.

                  array[j + 1] = key;

            }

      }

      // main method for testing the above method

      public static void main(String[] args) {

            // creating an array of integers

            Integer array[] = { 12, 22, -22, 76, 33, 8, 0, 1, 19, 7 };

            // printing array

            System.out.println("Array before sorting: ");

            for (int i = 0; i < array.length; i++) {

                  System.out.print(array[i] + " ");

            }

            System.out.println();

            // sorting the array using the first method we defined, in ascending

            // order (default order)

            insertionSort(array);

            // printing array again

            System.out.println("Array after sorting in ascending order: ");

            for (int i = 0; i < array.length; i++) {

                  System.out.print(array[i] + " ");

            }

            System.out.println();

            // creating an object of IntegerComparator

            IntegerComparator comparator=new IntegerComparator();

            // sorting the array using the second method we defined, using this

            // comparator

            insertionSort(array, comparator);

            // printing array again

            System.out

                        .println("Array after sorting in ascending order using comparator: ");

            for (int i = 0; i < array.length; i++) {

                  System.out.print(array[i] + " ");

            }

            System.out.println();

      }

}

//a class that implements Comparator interface to compare Integers

class IntegerComparator implements Comparator<Integer> {

      // returns a negative value if first<second, positive if first>second, 0 if

      // they are same

      public int compare(Integer first, Integer second) {

            return first - second;

      }

}

/*OUTPUT*/

Array before sorting:

12 22 -22 76 33 8 0 1 19 7

Array after sorting in ascending order:

-22 0 1 7 8 12 19 22 33 76

Array after sorting in ascending order using comparator:

-22 0 1 7 8 12 19 22 33 76

Add a comment
Know the answer?
Add Answer to:
23.8 (Generic insertion sort) Write the following two generic methods using insertion sort. The first method...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Answer please Exercice 3(25+ 20 pts); Sorting 1-Sorting is a classic subject in computer science. There...

    Answer please Exercice 3(25+ 20 pts); Sorting 1-Sorting is a classic subject in computer science. There are many sorting algorithms a. Complete the below code b.Add comments to the below code to explain each statement c. Write a main test then give the output screen of it 2- a-Write the following two generic methods using the below code. The first method sorts the elements using the Comparable interface and the second uses the Comparator interface. public static <E extends Comparable<E>>...

  • 1. Implement generic insertion sort public static <E extends Comparable<E>> void insertionSort(E[] list){ //implement body }...

    1. Implement generic insertion sort public static <E extends Comparable<E>> void insertionSort(E[] list){ //implement body } 2. Implement generic bubble sort public static <E extends Comparable<E>> void bubbleSort(E[] list){ //implement body } 3. Implement generic merge sort public static <E extends Comparable<E>> void mergeSort(E[] list){ //implement body } 4. Implement generic heap sort public static <E extends Comparable<E>> void heapSort(E[] list){ //implement body }

  • Program with generic merge sort and binary search method help. The programming language I'm using is...

    Program with generic merge sort and binary search method help. The programming language I'm using is Java. This program should show understanding generic merge sort methods and generic binary search methods in java. The execution should include at least 5 found items including one from the first three items in the sorted array and one from the last three items in the sorted array as well as at least two items not found Create a generic merge sort method that...

  • //Java (Sort ArrayList) Write the following method that sorts an ArrayList: public static > void sort(ArrayList...

    //Java (Sort ArrayList) Write the following method that sorts an ArrayList: public static > void sort(ArrayList list) Write a test program that does the following operations: 4. Creates an empty ArrayList of Integer elements; 5. Generates 20 integer values, drawn at random between 0 and 9 (included), and adds them to the array list; 6. Calls the method sort and prints both the original list, and the sorted one.

  • this is a generic class in java how implement sort method   public class ArrayBag<T> {   ...

    this is a generic class in java how implement sort method   public class ArrayBag<T> {    private T[] data;    private int manyItems; // TODO change and implement this method to use the generic type    // Sort the elements based on the comparator passed to this method    // You must use Selection Sort algorithm    public void sort(Comparator<T> comp) {                     } }

  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

  •   Given a bubble sort and the following array: [10,7,19,5,16] What are the values after the first...

      Given a bubble sort and the following array: [10,7,19,5,16] What are the values after the first iteration? Given an insertion sort and the following array: [50,5,35,70,6] What does the array look like after the first insertion:    Fill in the missing code for InsertionSort method // Insertion Sort method //sorts an array of Auto objects public static void insertionSort(Auto [] arr) { Auto temp; int j; for (int i=1; i<arr.length; i++) {     j=i;     temp=arr[i];                while (j!=0 &&(temp.getModel().compareTo(arr[[j-1].getModel())<0)...

  • Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement...

    Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement some list functionalities on an ArrrayList of generic type using type parameters in method definition Our goal for this lab is to continue using the divide and conquer approach of splitting a list into its head and tail and keep recursing on the tail (which happens to be smaller). However, instead of trying the approach on a string (a list of characters) we would...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT