| @ -0,0 +1,58 @@ | |||
| package net.jrtechs.www.Sorting; | |||
| import net.jrtechs.www.DataStructures.Lists.ArrayList.ArrayBackedList; | |||
| /** | |||
| * Created an array list which is able to sort | |||
| * itself upon request. | |||
| * | |||
| * @param <E> | |||
| * @author Jeffery Russell | |||
| */ | |||
| public class SortableList<E extends Comparable> extends ArrayBackedList<E> | |||
| { | |||
| /** Constant for an increasing list */ | |||
| public final int INCREASING_ORDER = 1; | |||
| /** Constant for a decreasing list */ | |||
| public final int DECREASING_ORDER = -1; | |||
| /** | |||
| * Creates a new list of default size | |||
| */ | |||
| public SortableList() | |||
| { | |||
| super(); | |||
| } | |||
| /** | |||
| * Creates a new list of non-default size | |||
| */ | |||
| public SortableList(int size) | |||
| { | |||
| super(size); | |||
| } | |||
| /** | |||
| * Sorts the list using insertion sort. | |||
| * | |||
| * @param sortOrder constant corresponding to sort type | |||
| */ | |||
| public void insertionSort(int sortOrder) | |||
| { | |||
| for(int i = 1; i < this.size(); i++) | |||
| { | |||
| int reverseIndex = i; | |||
| while(reverseIndex > 0 && this.get(reverseIndex-1) | |||
| .compareTo(this.get(reverseIndex)) == sortOrder) | |||
| { | |||
| this.swap(reverseIndex, reverseIndex-1); | |||
| reverseIndex--; | |||
| } | |||
| } | |||
| } | |||
| } | |||
| @ -0,0 +1,52 @@ | |||
| package net.jrtechs.www.sorting; | |||
| import net.jrtechs.www.Sorting.SortableList; | |||
| import org.junit.Test; | |||
| import static junit.framework.TestCase.assertNotNull; | |||
| import static junit.framework.TestCase.assertTrue; | |||
| /** | |||
| * Class for testing insertion sort | |||
| * | |||
| * @author Jeffery Russell 8-27-18 | |||
| */ | |||
| public class InsertionSortTest | |||
| { | |||
| @Test | |||
| public void testInitalization() | |||
| { | |||
| SortableList<Double> list = new SortableList<>(); | |||
| assertNotNull(list); | |||
| } | |||
| @Test | |||
| public void testInsertionSortAscending() | |||
| { | |||
| SortableList<Double> list = new SortableList<>(); | |||
| list.add(1.0); | |||
| list.add(0.0); | |||
| list.add(3.0); | |||
| list.add(-12.0); | |||
| list.insertionSort(list.INCREASING_ORDER); | |||
| assertTrue(list.get(0) == -12.0); | |||
| assertTrue(list.get(list.size() -1) == 3); | |||
| } | |||
| @Test | |||
| public void testInsertionSortDescending() | |||
| { | |||
| SortableList<Double> list = new SortableList<>(); | |||
| list.add(1.2); | |||
| list.add(1.0); | |||
| list.add(0.0); | |||
| list.add(3.0); | |||
| list.add(-12.0); | |||
| list.insertionSort(list.DECREASING_ORDER); | |||
| assertTrue(list.get(0) == 3.0); | |||
| assertTrue(list.get(list.size() -1) == -12); | |||
| } | |||
| } | |||