Skip to content

Commit 4709345

Browse files
committed
add Test for InsertionSort
1 parent 0adfcac commit 4709345

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package src.main.java.com.sorts;
2+
3+
public class InsertionSort {
4+
5+
/**
6+
* This method implements the Generic Insertion Sort
7+
* Sorts the array in increasing order
8+
*
9+
* @param array The array to be sorted
10+
**/
11+
public <T extends Comparable<T>> T[] sort(T[] array) {
12+
for (int j = 1; j < array.length; j++) {
13+
14+
// Picking up the key(Card)
15+
T key = array[j];
16+
int i = j - 1;
17+
18+
while (i >= 0 && SortUtils.less(key, array[i])) {
19+
array[i + 1] = array[i];
20+
i--;
21+
}
22+
// Placing the key (Card) at its correct position in the sorted subarray
23+
array[i + 1] = key;
24+
}
25+
return array;
26+
}
27+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package src.test.java.com.sorts;
2+
3+
4+
import org.junit.Assert;
5+
import org.junit.Test;
6+
import src.main.java.com.sorts.InsertionSort;
7+
8+
import java.util.Arrays;
9+
10+
public class InsertionSortTest {
11+
12+
@Test
13+
public void insertionSortTest() {
14+
InsertionSort insertionSort = new InsertionSort();
15+
Integer[] unsortedInt = new Integer[]{0, 5, 9, 2, 1, 3, 4, 8, 6, 7};
16+
Integer[] sortedInt = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
17+
System.out.println(Arrays.toString(insertionSort.sort(unsortedInt)));
18+
19+
Assert.assertArrayEquals(sortedInt, insertionSort.sort(unsortedInt));
20+
21+
Character[] unsortedChar = new Character[]{'f', 'h', 'c', 'a', 'b', 'd', 'g', 'e'};
22+
Character[] sortedChar = new Character[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
23+
System.out.println(Arrays.toString(insertionSort.sort(unsortedChar)));
24+
25+
Assert.assertArrayEquals(sortedChar, insertionSort.sort(unsortedChar));
26+
}
27+
}

0 commit comments

Comments
 (0)