Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

need help with this java program Write a version of insertion sort that is capab

ID: 3812649 • Letter: N

Question

need help with this java program

Write a version of insertion sort that is capable of sorting an array of objects of any class

that implements the Comparable interface. Write Junit tests to thoroughly test your method. Please note that you will not

receive credit if you do not have any test cases.

Example code/output

Integer[] test = {1, 0, -4, -6, 2, 10};

insertionSort(test);

// test is now {-6, -4, 0, 1, 2, 10}

Student bob = new Student(“Bob”, 4.0);

Student alice = new Student(“Alice”, 3.5);

Student carol = new Student(“Carol”, 3.5);

Student dave = new Student(“Dave”, 3.7);

Student[] test = {bob, alice, carol, dave};

// assume Students are compared first on GPA and then on name

// test is now {bob, dave, alice, carol}

Explanation / Answer

//Make the below class and store as SortUsingComparable.java
public class SortUsingComparable {

public static void insertionSort(Comparable[] ar) {

for (int i=0; i != ar.length; i = i+1) {
Comparable insert = ar[i];
int j = i;
while (j != 0 && greater(ar[j-1], insert)) {
ar[j] = ar[j-1]; j = j-1;
}
ar[j] = insert ;
}
}

private static boolean greater(Comparable left, Object right)
{ return left.compareTo(right) == 1; }
}

//Make below class and store as Check.java
public class Check implements Comparable {

String name;
int age;

public Check(String name, int age)
{ this.name = name; this.age = age; }

public String getName() { return name; }
public int getAge() { return age; }
public String toString() { return "Name: " + name + " Age: " + age; }

public int compareTo(Object item) {

int itemAge = ((Check) item).getAge();
int result;

if (getAge() < itemAge) { result = -1; }
else if (getAge() > itemAge) { result = 1; }
else { result = 0; }
return result;
}

}

import Check;
import SortUsingComparable;
public class HelloWorld{

public static void main(String[] args) {
Check[] c = new Check[5];


c[0] = new Check("First", 29);
c[1] = new Check("Second", 15);
c[2] = new Check("Rumpel", 256);
c[3] = new Check("Rum", 25);
c[4] = new Check("Ruml", 26);
  
  
SortUsingComparable.insertionSort(c); // sort p[] by age

for (int i=0; i != c.length; i = i+1)
{ System.out.println( c[i] ); }
}
}