Skip to content

Commit a7654bd

Browse files
committed
add insert sort implemention with Java
1 parent f0ac0b1 commit a7654bd

File tree

4 files changed

+33
-0
lines changed

4 files changed

+33
-0
lines changed

src/java/lib/hamcrest-core-1.3.jar

44 KB
Binary file not shown.

src/java/lib/junit-4.12.jar

308 KB
Binary file not shown.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package huson;
2+
3+
import java.util.Arrays;
4+
5+
public class InsertionSort implements ISort
6+
{
7+
@Override
8+
public int[] sort(int[] arr)
9+
{
10+
int[] result = Arrays.copyOf(arr, arr.length);
11+
for (int i = 1; i < result.length; i++) {
12+
int insertValue = result[i];
13+
int j = i;
14+
while (j > 0 && insertValue < result[j - 1] ) {
15+
result[j] = result[j - 1];
16+
j--;
17+
}
18+
if (j != i) {
19+
result[j] = insertValue;
20+
}
21+
}
22+
return result;
23+
}
24+
}

src/java/test/HusonSortTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import huson.BubbleSort;
2+
import huson.InsertionSort;
23
import huson.SelectionSort;
34
import org.junit.After;
45
import org.junit.Assert;
@@ -47,6 +48,14 @@ public void testSelectionSort()
4748
Assert.assertArrayEquals(sortedArray, new SelectionSort().sort(array));
4849
}
4950

51+
@Test
52+
public void testInsertionSort()
53+
{
54+
System.out.println("sortedArray = \n" + Arrays.toString(sortedArray));
55+
System.out.println("selectionSortedArray = \n" + Arrays.toString(new InsertionSort().sort(array)));
56+
Assert.assertArrayEquals(sortedArray, new InsertionSort().sort(array));
57+
}
58+
5059
private int[] generateRandomArray(int number, int min, int max)
5160
{
5261
int[] result = new int[number];

0 commit comments

Comments
 (0)