70.2k views
1 vote
Create a public class named InsertionSorter. It should provide one class method sort. sort accepts an array of Comparables and sorts them in ascending order. You should sort the array in place, meaning that you modify the original array, and return the number of swaps required to sort the array as an int. That's how we'll know that you've correctly implemented insertion sort. If the array is null you should throw an IllegalArgumentException. You can assume that the array does not contain any null values.

To receive credit implement insertion sort as follows. Have the sorted part start at the left and grow to the right. Each step takes the left-most value from the unsorted part of the array and move it leftward, swapping elements until it is in the correct place. Do not swap equal values. This will make your sort unstable and cause you to fail the test suites.

User Joel Hoff
by
6.1k points

1 Answer

4 votes

Answer:

Step-by-step explanation:

The following code is written in Java it uses an insertion sort algorithm to sort a Comparable array that is passed as an input. The method itseld returns the number of changes that need to be made in order to fully sort the array.

class InsertionSorter {

private static Object IllegalArgumentException;

public static void main(String[] args) throws Throwable {

Comparable[] myarr = {1, 6, 15, 2, 5, 3, 8, 33, 10};

System.out.println(insertionSort(myarr));

}

public static int insertionSort(Comparable[] array) throws Throwable {

try {

int i, j;

Comparable newValue;

int count = 0;

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

newValue = array[i];

j = i;

while (j > 0 && (array[j - 1].compareTo(newValue)>0)) {

array[j] = array[j - 1];

j--;

count += 1;

}

array[j] = newValue;

}

return count;

} catch (Exception e) {

throw (Throwable) IllegalArgumentException;

}

}

}

Create a public class named InsertionSorter. It should provide one class method sort-example-1
User Anaval
by
5.8k points