add Test for InsertionSort
This commit is contained in:
parent
0adfcaca7a
commit
47093451ac
27
src/main/java/com/sorts/InsertionSort.java
Normal file
27
src/main/java/com/sorts/InsertionSort.java
Normal file
@ -0,0 +1,27 @@
|
||||
package src.main.java.com.sorts;
|
||||
|
||||
public class InsertionSort {
|
||||
|
||||
/**
|
||||
* This method implements the Generic Insertion Sort
|
||||
* Sorts the array in increasing order
|
||||
*
|
||||
* @param array The array to be sorted
|
||||
**/
|
||||
public <T extends Comparable<T>> T[] sort(T[] array) {
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
|
||||
// Picking up the key(Card)
|
||||
T key = array[j];
|
||||
int i = j - 1;
|
||||
|
||||
while (i >= 0 && SortUtils.less(key, array[i])) {
|
||||
array[i + 1] = array[i];
|
||||
i--;
|
||||
}
|
||||
// Placing the key (Card) at its correct position in the sorted subarray
|
||||
array[i + 1] = key;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
}
|
27
src/test/java/com/sorts/InsertionSortTest.java
Normal file
27
src/test/java/com/sorts/InsertionSortTest.java
Normal file
@ -0,0 +1,27 @@
|
||||
package src.test.java.com.sorts;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import src.main.java.com.sorts.InsertionSort;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class InsertionSortTest {
|
||||
|
||||
@Test
|
||||
public void insertionSortTest() {
|
||||
InsertionSort insertionSort = new InsertionSort();
|
||||
Integer[] unsortedInt = new Integer[]{0, 5, 9, 2, 1, 3, 4, 8, 6, 7};
|
||||
Integer[] sortedInt = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
System.out.println(Arrays.toString(insertionSort.sort(unsortedInt)));
|
||||
|
||||
Assert.assertArrayEquals(sortedInt, insertionSort.sort(unsortedInt));
|
||||
|
||||
Character[] unsortedChar = new Character[]{'f', 'h', 'c', 'a', 'b', 'd', 'g', 'e'};
|
||||
Character[] sortedChar = new Character[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
|
||||
System.out.println(Arrays.toString(insertionSort.sort(unsortedChar)));
|
||||
|
||||
Assert.assertArrayEquals(sortedChar, insertionSort.sort(unsortedChar));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user